Reputation: 2654
I would like to either extend or append a list to the content of another list: I've got the following:
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
I would like to see the following result when the 'result' is printed out in the above code (each in newline):
['AA', 1.11, 'XX', 7.77]
['BB', 2.22, 'YY', 8.88]
['CC', 3.33, 'ZZ', 9.99]
Many thanks in advance.
Upvotes: 2
Views: 358
Reputation: 123478
Here's one way:
import itertools
for a, b, c in itertools.izip(l, ls, m):
result = list(a) + list(b) + [c]
print result
The output:
['AA', 1.1100000000000001, 'XX', 7.7699999999999996, 'first']
['BB', 2.2200000000000002, 'YY', 8.8800000000000008, 'second']
['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002, 'third']
Upvotes: 0
Reputation: 2946
You want the zip function:
>>> 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]
1: http://docs.python.org/library/functions.html#zip "zip
Upvotes: 2
Reputation: 879251
All you need is 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]
Upvotes: 11