我想借此每兩個數字,它們相乘。
它總是最好要發佈:
- 你的出發數據。
[1, 2, 3, 4]
1 * 2 => 2
3 * 4 => 12
,那麼你可以這樣做::
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
$ 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
- 你想
如果你想乘數對在一起,像這樣做的實際結果
基於您的代碼在這裏
:
counter = 0
for n in line:
counter *= int(n)
也許你想要的東西,像下面這樣:
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)
[1, 1, 1]
result = funcs.reduce(op.mul, every_other) #multiply all the numbers in every_other together, reducing them to one number
print(result)
1
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)
[2, 2, 2]
result = funcs.reduce(op.mul, every_other)
print(result)
8
什麼是你期望的輸出? –
我想得到624 4875,等等,只是讓他們乘以等等。 – user5566334
如果一行包含5個數字,該怎麼辦? –