我需要在同一个数组中的每个元素中添加数组中的每个元素,然后将结果添加到新数组中。我试过了
my_list = []
for filename in [my_file]:
with open(filename) as f:
my_list += [int(i) for line in f for i in line.split()]
answer = []
for elem in my_list:
answer += [elem + elem]
print answer
当my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
时,程序会打印[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
,这是不正确的。我怎样才能解决这个问题?
答案 0 :(得分:1)
你可以试试这个:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
answer = [i+a for i in my_list for a in my_list]
输出:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]