我想将列表扩展或附加到另一个列表的内容: 我有以下内容:
l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45))
ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]
m = ['first', 'second', 'third']
for i in range(len(l)):
result = []
for n in m:
if n == "first":
r=[]
for word, number in ls[i]:
temp = [word, number]
r.append(temp)
for t in r:
result.extend(t)
print result
我希望在上面的代码中打印出'result'时会看到以下结果(每个都在换行符中):
['AA', 1.11, 'XX', 7.77]
['BB', 2.22, 'YY', 8.88]
['CC', 3.33, 'ZZ', 9.99]
非常感谢提前。
答案 0 :(得分:11)
您所需要的只是zip:
l = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33))
ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]
for x,y in zip(l,ls):
print(list(x+y))
# ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]
# ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]
# ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002]
答案 1 :(得分:2)
您需要zip功能:
>>> for x in zip(l, ls):
>>> list1, list2 = x
>>> print list1 + list2
>>> ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]
>>> ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]
>>> ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002]
答案 2 :(得分:0)
这是一种方式:
import itertools
for a, b, c in itertools.izip(l, ls, m):
result = list(a) + list(b) + [c]
print result
输出:
['AA', 1.1100000000000001, 'XX', 7.7699999999999996, 'first']
['BB', 2.2200000000000002, 'YY', 8.8800000000000008, 'second']
['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002, 'third']