如何选择偶数和奇数的整数并获得它们的总数

  • 本文关键字:整数 何选择 选择 python
  • 更新时间 :
  • 英文 :


好吧,我重新开始,我会照原样承受我所拥有的一切。

的数字

#This program writes 1 line of 12 random integers, each in the
#range from 1-100 to a text file.
def main():
    import random
    #Open a file named numbers.txt.
    outfile = open('numbers.txt', 'w')
    #Produce the numbers
    for count in range(12):
        #Get a random number.
        num = random.randint(1, 100)
        #Write 12 random intergers in the range of 1-100 on one line
        #to the file.
        outfile.write(str(num) + " ")
    #Close the file.
    outfile.close()
    print('Data written to numbers.txt')
#Call the main function
main()

上面的代码生成一个文本文件,上面写着:

60 90 75 94 54 12 10 45 60 92 47 65

上面的数字是由一个空格分隔的12个随机生成的整数。

如果我去掉空格,在第二个脚本中会更容易吗?

读取的数字

#This program reads 12 random integers, outputs each number
#to its own line and then outputs the total of the even and odd  intergers.
def main():
    #Open a file named numbers.txt.
    infile = open('numbers.txt', 'r')
    #Read/process the file's contents.
    file_contents = infile.readline()
    numbers = file_contents.split(" ")
    odd = 0
    even = 0
    num = int(file_contents)
    for file_contents in numbers:
        if num%2 == 0:
            even += num
        else:
            odd += num
    #Close the file.
    infile.close()
    #Print out integer totals
    print('The total of the even intergers is: ', even)
    print('The total of the odd intergers is: ', odd)
#Call the main function
main()

我从上面试图处理偶数和奇数总数的脚本中收到的错误是:

Traceback (most recent call last):
  File "numbersread.py", line 29, in <module>
    main()
  File "numbersread.py", line 14, in main
    num = int(file_contents)
ValueError: invalid literal for int() with base 10: '60 90 75 94 54 12 10 45 60 92 47 65 '

我不知道我做错了什么。

假设您有一个类似["1","2","3"...] 的列表

odd = sum(int(x) for x in  numbers if x % 2)
even = sum(int(x) for x in  numbers if not x % 2)

最好的方法是使用with打开文件并首先映射到int:

with open('numbers.txt') as f: # closes you files automatically
    numbers = map(int,f.read().split())

    odd = sum(x for x in numbers if x % 2) 
    even = sum(x for x in numbers if not x % 2)

如果你有一个非常大的文件,你会在每一行上迭代,并边走边求和。

此外,如果您只想用f.readline().split() 替换第一行f.read().split(),则只能使用readline读取单行

sum(x for x in numbers if x % 2)是生成器表达式,当为生成器对象调用next()方法时,生成器表达式中使用的变量将延迟求值

对我来说,这看起来像是家庭作业,但这是我用来代替while循环的内容

for num_str in numbers:
  num = int(num_str)
  if num%2 == 0: #Even
    even += num
  else:
    odd += num

相关内容

  • 没有找到相关文章

最新更新