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

时间:2015-02-19 19:28:29

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

4 个答案:

答案 0 :(得分:2)

从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) 
它可能比freddies回答慢一点...... 但这是一个很好的模式知道

或聊天中的@JonClements pointed out

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

是一种巧妙的方式

答案 1 :(得分:1)

为了检查数字是奇数还是偶数,你应该使用模数运算符。

如果一个整数可以被2整除,它将是偶数,否则就是奇数。 所以......

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

答案 2 :(得分:1)

将此数字用作偶数

def even_numbers(maximum):
    return_string = ""
    for x in range(2,maximum+1,2):
        return_string += str(x) + " "
    return return_string.strip()

答案 3 :(得分:0)

# 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)