我在
列中有一个数字列表10,12,13
我想编写一个python程序,可以通过以下方式添加这些数字:10+12=22, 10+13=23, 12+13=25
任何人都可以提出任何建议如何做到这一点。
感谢
答案 0 :(得分:2)
使用combinations
中的itertools
,这可以相当简单地完成。对于列表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]
答案 1 :(得分:0)
这可能有效(使用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()
答案 2 :(得分:0)
如果您因某种原因不想使用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))