<blockquote>
<p>I would like to take every two numbers and multiply them together.</p>
</blockquote>
<p>最好发布:</p>
<ol>
<li>你的起始数据。你知道吗</li>
<li>你想要的实际结果</li>
</ol>
<p>如果要将成对的数字相乘,如下所示:</p>
<pre><code>[1, 2, 3, 4]
1 * 2 => 2
3 * 4 => 12
</code></pre>
<p>然后你可以这样做:</p>
<pre><code>import csv
import itertools as it
with open('data.txt', newline='') as f:
csv_reader = csv.reader(f, delimiter=' ')
for row in csv_reader:
print(row) #=> ['1', '2', '3', '4']
every_other0 = it.islice(row, 0, False, 2) #Produces items from the row at index 0, 2, etc.
every_other1 = it.islice(row, 1, False, 2) #Produces items from the row at index 1, 3, etc.
while True:
str1 = next(every_other0, None) #if there are no more items in every_other0, return False
str2 = next(every_other1, None) #if there are no more items in every_other1, return False
if str1 and str2: #if either str1 or str2 is False, the condition is False
num1 = int(str1)
num2 = int(str2)
print("{} * {} = {}".format(num1, num2, num1*num2))
else:
break
</code></pre>
<hr/>
<pre><code>$ cat data.txt
1 2 3 4
5 6 7 8
~/python_programs$ python3.4 prog.py
['1', '2', '3', '4']
1 * 2 = 2
3 * 4 = 12
['5', '6', '7', '8']
5 * 6 = 30
7 * 8 = 56
</code></pre>
<hr/>
<p>根据您的代码:</p>
<pre><code>counter = 0
for n in line:
counter *= int(n)
</code></pre>
<p>也许你想要的是如下的东西:</p>
<pre><code>import operator as op
import functools as funcs
import csv
with open('data.txt', newline='') as f: #opens the file and automatically closes the file when the block is exited for any reason including if an exception occurs
csv_reader = csv.reader(f, delimiter=' ')
for row in csv_reader:
every_other = [int(item) for item in row[::2] ] #=> row[::2] is equivalent to row[0:len(row):2], which means get the element at index 0, then add the step, 2, to the index value, and get the next element, etc., and stop at the index len(row).
print(every_other)
</code></pre>
<hr/>
<pre><code>[1, 1, 1]
</code></pre>
<hr/>
<pre><code> result = funcs.reduce(op.mul, every_other) #multiply all the numbers in every_other together, reducing them to one number
print(result)
</code></pre>
<hr/>
<pre><code>1
</code></pre>
<hr/>
<pre><code> every_other = [int(item) for item in row[1::2] ] #=> row[1::2] is equivalent to row[1:len(row):2], which means start at index 1 and stop at a the end of row, and get the element at index 1; add the step, 2, to the index value, and get the element at that index, etc.
print(every_other)
</code></pre>
<hr/>
<pre><code>[2, 2, 2]
</code></pre>
<hr/>
<pre><code> result = funcs.reduce(op.mul, every_other)
print(result)
</code></pre>
<hr/>
<pre><code>8
</code></pre>