Python 扩展/追加列表
我想将一个列表扩展或附加到另一个列表的内容: 我有以下几点:Python 扩展/追加列表,python,Python,我想将一个列表扩展或附加到另一个列表的内容: 我有以下几点: 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:
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
我希望在上述代码中打印“结果”时看到以下结果(每行换行):
非常感谢。您只需要:
您需要以下功能:
>>> 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]
:“zip这里有一种方法:
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']
非常感谢,但很抱歉我忘了提到l可以是l=('AA',1.11,'DD',1.2),('BB',2.22,'EE',2.3),('CC',3.33,'FF',3.45))。我不认为zip()不过在这种情况下有效。有办法吗?是的,你是对的。确实有效。我输入的东西不对。非常感谢,unutbu.BTW,PEP 8建议不要将
l
用作变量名,因为它类似于1
。
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']