python - 用Python计算文件中奇数和偶数的总数

标签 python python-3.4

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/

相关文章:

python - 使用 python 读取 csv 文件让我到达最后一行

python - 没有名为请求 PythonAnywhere 错误的模块

python - 用于 Python 图像处理的类似 Blockproc 的函数

python - asyncio 超时终止子进程

django - 使用自定义管理站点自动注册 Django 身份验证模型

python - 凌乱的 Python 安装? (OS X)

Python - 按修改日期 [小时] 分组文件

python - 如何在Python列表中对许多类别组合(72个变量)进行分类

linux - Python3 没有那个文件或目录

Python 高效排序字典中的并行列表