代码将文件分配到列表中,然后打印值并分为组

发布于 2025-01-26 05:11:20 字数 1314 浏览 1 评论 0原文

需要帮助读取文件并将数字分为int值的代码。我已经能够执行其他功能,但是在以下功能方面遇到困难。我需要让它打印序列的正值和负值...

printIntegersequenceInformation:此函数以整数序列的列表(整数列表)接收,并且不会返回任何值。该函数打印以下信息(您必须使用下面提供的输出消息):

Values: 1 3 5 7 9 11
num of Values: 6
num Positive Values: 6
num Negative Values: 0

代码:

def printIntegerSequenceInformation(ListOfSequences):
  p_count=0
  n_count=0
  i=0
  print("values:",end=" ")
  l = ListOfSequences
  while i<len(l):
    print(l[i],end=" ")
    if(l[i]>0):
      p_count+=1
    elif(l[i]<0):
      n_count+=1
    i+=1
  print("\n# of values:",len(ListOfSequences))
  print("# Positive values:",p_count)
  print("# Negative values:",n_count)

这是我的其他功能。

def readFromFile(filename):
  fh = open(filename)
  ListOfSequences = []
  for line in fh:
    if line[-1] == '\n':
      line = line[:-1]
    sequence = line.split(" ")
    for i in range(len(sequence)):
      sequence[i] = int(sequence[i])
    ListOfSequences.append(sequence)
  fh.close()
  return ListOfSequences

def printIntegerSequence(ListOfSequences):
  for no, sequence in enumerate(ListOfSequences, start=1):
    print(f"Sequence #{no}")
    sequence = list(map(str, sequence))
    print(" ".join(sequence))

Need help with a code that reads a file and sorts the numbers into sequences as int values. I have been able to do the other functions but am having difficulty with the following function. I need to have it print the positive and negative values of a sequence...

printIntegerSequenceInformation: This function receives as a parameter the list (list of integers) with an integer sequence and does not return any value. The function prints the following information (you must use the output messages presented below):

Values: 1 3 5 7 9 11
num of Values: 6
num Positive Values: 6
num Negative Values: 0

Code:

def printIntegerSequenceInformation(ListOfSequences):
  p_count=0
  n_count=0
  i=0
  print("values:",end=" ")
  l = ListOfSequences
  while i<len(l):
    print(l[i],end=" ")
    if(l[i]>0):
      p_count+=1
    elif(l[i]<0):
      n_count+=1
    i+=1
  print("\n# of values:",len(ListOfSequences))
  print("# Positive values:",p_count)
  print("# Negative values:",n_count)

Here are my other functions for the program.

def readFromFile(filename):
  fh = open(filename)
  ListOfSequences = []
  for line in fh:
    if line[-1] == '\n':
      line = line[:-1]
    sequence = line.split(" ")
    for i in range(len(sequence)):
      sequence[i] = int(sequence[i])
    ListOfSequences.append(sequence)
  fh.close()
  return ListOfSequences

def printIntegerSequence(ListOfSequences):
  for no, sequence in enumerate(ListOfSequences, start=1):
    print(f"Sequence #{no}")
    sequence = list(map(str, sequence))
    print(" ".join(sequence))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文