开发者

join two lists by interleaving

I have a list that I create by parsing some text. Let's say the list looks like

charlist = ['a', 'b', 'c']

I would like to 开发者_JS百科take the following list

numlist = [3, 2, 1]

and join it together so that my combined list looks like

[['a', 3], ['b', 2], ['c', 1]]

is there a simple method for this?


If you want a list of lists rather than a list of tuples you could use:

map(list,zip(charlist,numlist))


The zip builtin function should do the trick.

Example from the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]


Here's another easy way to do it.

charlist = ['a', 'b', 'c']
numlist = [3, 2, 1]
newlist = []

for key, a in enumerate(charlist):
    newlist.append([a,numlist[key]])

Content of newlist: [['a', 3], ['b', 2], ['c', 1]]


You could try the following, though I am sure there are going to be better approaches:

l1 = ['a', 'b', 'c']
l2 = [1, 2, 3]    
l = []
for i in 1:length(l1):
    l.append([l1[i], l2[i]])

All the best.


p=[] 
for i in range(len(charlist)): 
    p.append([charlist[i],numlist[i]])
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜