开发者

Combining lists with python using two lists

开发者 https://www.devze.com 2023-02-10 12:46 出处:网络
I have two lists: f= [\'A\', \'A\'] d = [(2096, 2开发者_高级运维22, 2640), (1494, 479, 1285)] I want a list!

I have two lists:

f= ['A', 'A']  
d = [(2096, 2开发者_高级运维22, 2640), (1494, 479, 1285)]

I want a list!

LL = [('A', 2096, 222, 2640), ('A', 1494, 479, 1285)]

I am close with dic = zip(f,d)

but this give me this:

[('A', (2096, 222, 2640)), ('A', (1494, 479, 1285))]

How can i get LL?


Try:

LL = [ (x,) + y for x, y in zip(f, d) ]

This iterates through the convoluted arrays and adds the string outside the tuple to the tuple (by creating a new tuple, due to the fact tuples are immutable).


the zip command does that along with dict:

>>>dict(zip([1,2,3],[1,2,3]))
{1:1,2:2,3:3}


You can also do this with map() instead of zip()

LL = map(lambda x,y:(x,)+y, f, d)

(x,) is equivalent to tuple(x)

LL = map(lambda x,y:tuple(x)+y, f, d)


[(x,) + y for x,y in zip(f, d)]


In fact you have a list of strings and a list of tuples. Tuples are immutable, so you will have to reconstruct each tuple.

For only 2 items you can try:

[tuple(f[0])+d[0], tuple(f[1])+d[1]]

For N number of items look for "list comprehension", for example here: http://docs.python.org/tutorial/datastructures.html or build them up using a loop if that is more understandable.

0

精彩评论

暂无评论...
验证码 换一张
取 消