好吧,我开始新鲜,我将承担我拥有的一切。
NumbersMake.py
#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个随机产生的整数,中间用空格隔开。
如果删除空格,在第二个脚本中会更容易吗?
NumbersRead.py
#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)
如果文件很大,则需要遍历每一行并进行累加。
另外,如果只希望第一行将
readline
替换为f.read().split()
,则仅使用f.readline().split()
读取一行sum(x for x in numbers if x % 2)
是generator expression,当对生成器对象调用next()方法时,对生成器表达式中使用的变量进行延迟计算关于python - 如何选择偶数和奇数整数并求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28888631/