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

Calculating the totals of odd and even numbers from a file in Python

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 循环计算了总数,但我不知道如何修改它以使其完成我想要它做的事情。

为了检查一个数是奇数还是偶数,您应该使用取模运算符。

一个整数能被2整除就是偶数,否则就是奇数。 所以...

while line != '':
    if int(line) % 2 == 0:
         evenTotal += int(line)
    else
        oddTotal += int(line)
    line = infile.readline()

在 itertools 中,您可以使用分区配方将偶数和奇数进行分区,然后return它们的总和

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) 

它可能会比 freddies 的回答慢一点... 但这是一个很好的模式

或作为@JonClements pointed out 在聊天中

r = range(11)
d = dict.fromkeys([0, 1], 0)
for i in r: d[i % 2] += i

是一种巧妙的方法

偶数用这个

def even_numbers(maximum):
    return_string = ""
    for x in range(2,maximum+1,2):
        return_string += str(x) + " "
    return return_string.strip()
# With this program in Python you will check a document for even and odd numbers and
# also it skips any text 
# It also writes 2 extra files Oddfile and Evenfile
import re

fhand = open('numbers.txt')  # file with numbers odd/even or even filled with text
text = fhand.read()
y = re.findall('[0-9]+', text)
sumeven = 0
sumodd = 0
Even = []
Odd = []
Oddfile=open('Oddfile.txt','w')
Evenfile=open('Evenfile.txt','w')
for number in y:
    if (int(number) % 2) == 0:# Checks if the number is even
        sumeven = sumeven + int(number)
        Even.append(int(number))
        Evenfile.write(str(number) + '\n')
    if (int(number) % 2) == 1:# Checks if the number is odd
        sumodd = sumodd + int(number)
        Odd.append(int(number))
        Oddfile.write(str(number) + '\n')

print("Even List is : ", Even)
print("Odd List is : ", Odd)