我想将子列表拆分为其元素

时间:2017-04-15 15:07:56

标签: python list

import sys
su_pri=0
su_sc=0
n = int(raw_input().strip())
m=0

j=n-1
count=1
diff=0
a = []
for a_i in range(n):
    a_temp = map(int,raw_input().strip().split(' '))
    a.append(a_temp)
print a
while(m<=len(a)):
    su_pri=sum(su_pri,int(a[m]))
    m=m+n+1
while(count<=n):
    su_sc=su_sc+a[j]
    j=j+n-1
diff=abs(su_pri-su_sc)
print diff

如果n = 3则列表为

3 11 2 4 4 5 6 10 8 -12 名单是 [[11,2,4],[4,5,6],[10,8,-12]] 我想将所有元素存储到长度= 9的单个列表中(在这种情况下) 我怎样才能做到这一点??? 请告诉我

4 个答案:

答案 0 :(得分:1)

创建新列表并将它们添加到一起

newdiff = []
for eachlist in diff:
    newdiff += eachlist
print newdiff

答案 1 :(得分:0)

例如:

a = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
b = a[0] + a[1] + a[2]

答案 2 :(得分:0)

您希望将数组中的每个元素相互添加。 Something like this maybe?希望有所帮助:)

答案 3 :(得分:0)

我认为您正在尝试在python中展平列表列表,我发现post非常有帮助。

l =  [[11, 2, 4], [4, 5, 6], [10, 8, -12]] #the list of lists to be flattened

flattenedList = [item for sublist in l for item in sublist]