擅长:python、mysql、java
<p>第一步是正确地从文件(程序失败的地方)中获取数字,然后将它们添加到新列表中。为了使程序更健壮,我们将捕获一个微不足道的边缘情况(当两个列表的参数数不相同时),作为奖励,您不必硬编码每个文件中的行数:</p>
<pre><code>from itertools import zip_longest
try:
with open("file1") as file1, open("file2") as file2:
numbers1 = [int(line) for line in file1.readlines()]
numbers2 = [int(line) for line in file2.readlines()]
result = [line[0] + line[1] for line in zip_longest(numbers1, numbers2, fillvalue=0)]
except FileNotFoundError:
print("Error opening files")
</code></pre>
<p>样本测试:</p>
<p>文件1:</p>
<pre><code>7
1
5
9
7
9
10
3
10
8
</code></pre>
<p>文件2:</p>
<pre><code>9
9
8
2
8
5
2
8
9
</code></pre>
<pre><code>>>> result
[16, 10, 13, 11, 15, 14, 12, 11, 19, 8]
</code></pre>
<p>您必须注意,文件的行数不同,file1(10)、file2(9),我举了这个例子来说明您的情况下的不确定程度:</p>
<blockquote>
<p>both have about 10 lines of random numbers</p>
</blockquote>