[英]adding numbers in a column in python
我在像這樣的列中有一個數字列表
10,12,13
我想編寫一個Python程序,可以通過以下方式添加這些數字: 10+12=22, 10+13=23, 12+13=25
任何人都可以提出任何建議。 謝謝
使用itertools
combinations
可以相當輕松地完成。 對於列表a
,您可以像這樣獲得n
元素的所有和
from itertools import combinations
def sum_of_size(a, n):
return map(sum, combinations(a, n))
編輯 :如果您使用的是python 3,請改用它
from itertools import combinations
def sum_of_size(a, n):
return list(map(sum, combinations(a, n)))
以你的例子
sum_of_size([10, 12, 13], 2)
# => [22, 23, 25]
這可能有效(使用Python 2.7):
x = [10,12,13]
for i in range(len(x)):
for j in range(i+1, len(x)):
print x[i],' + ', x[j], ' = ', x[i]+x[j]
輸出:
10 + 12 = 22
10 + 13 = 23
12 + 13 = 25
已更新:假設文件有一行:10、12、13
import csv
f = open("test.dat", 'r')
try:
reader = csv.reader(f)
for row in reader:
# convert array of string to int
# http://stackoverflow.com/a/7368801/5916727
# For Python 3 change the below line as explained in above link
# i.e. results = list(map(int, results))
results = map(int, row)
for i in range(len(results)):
for j in range(i+1, len(results)):
print (results[i]+results[j])
finally:
f.close()
如果由於某種原因不想使用itertools,可以通過這種方式實現。 通過給出的示例結果,我已經假定您要執行的操作:-
ColumnOfNumbers = [10,12,13]
def ListAddition(ColumnOfNumbers):
#check if the list is longer than one item
if len(ColumnOfNumbers)<=1:
return "List is too short"
#Define an output list to append results to as we iterate
OutputList = []
#By removing a number from the list as we interate we stop double results
StartNumber = 0
#Create a function to iterate - this is one less than the length of the list as we need pairs.
for x in range(len(ColumnOfNumbers)-1):
#Remove the first number from the list and store this number
StartNumber = ColumnOfNumbers[0]
ColumnOfNumbers.pop(0)
#Iterate through the list adding the first number and appending the result to the OutputList
for y in ColumnOfNumbers:
OutputList.append(StartNumber + y)
return OutputList
#Call the List Addition Function
print (ListAddition(ColumnOfNumbers))
如果您想讓python從數字列文件中生成此列表,請嘗試以下操作:-
ColumnOfNumbers = []
file1 = open('test.dat','r')
for line in file1:
ColumnOfNumbers.append(int(line))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.