def main():
infile = open('numbers.txt','r')
evenTotal = 0
oddTotal = 0
line = infile.readline()
while line != '':
total += int(line)
line = infile.readline()
print('The total for the even numbers is',evenTotal)
print('The total for the odd numbers is',oddTotal)
infile.close()
print('All done!')
main()
我试图让程序从其目录中的文件中读取数字,然后分离、计算并显示两组的总数。我遇到的麻烦是中间的赔率和偶数识别部分。我确实知道我在中间编写的 while 循环计算总数,但我不知道如何修改它以使其执行我想要的操作。
最佳答案
在 itertools 中,您可以使用分区配方来分区为偶数和奇数,并返回它们的总和
from itertools import ifilterfalse,imap,ifilter,tee
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return ifilterfalse(pred, t1), ifilter(pred, t2)
def is_odd(x):
return bool(x%2)
list_of_ints = imap(int,filter(lambda x:x.strip().isdigit(),infile))
odds, evens= partition(is_odd,list_of_ints)
print sum(evens),sum(odds)
它可能会比弗雷迪的回答慢一点...... 但这是一个值得了解的好模式
或@JonClements pointed out在聊天中
r = range(11)
d = dict.fromkeys([0, 1], 0)
for i in r: d[i % 2] += i
这是一个很好的方法
关于python - 用Python计算文件中奇数和偶数的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615180/