好的我开始新鲜,我将承担我所拥有的一切。
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 '
我不知道我做错了什么。
答案 0 :(得分:2)
假设您有一个类似["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 ()方法时会被懒惰地计算
答案 1 :(得分:0)
这看起来很像我的家庭作业,但这就是我用来代替你的while循环
for num_str in numbers:
num = int(num_str)
if num%2 == 0: #Even
even += num
else:
odd += num