Merge two lists by alternating

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

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

I would like to take the following list

 numlist = [3, 2, 1] 

and put it together so that my combo box looks like

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

Is there an easy way to do this?

+4
source share
5 answers

The zip built-in 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)] 
+7
source

If you need a list of lists, not a list of tuples, you can use:

 map(list,zip(charlist,numlist)) 
+9
source

Here is another easy way to do this.

 charlist = ['a', 'b', 'c'] numlist = [3, 2, 1] newlist = [] for key, a in enumerate(charlist): newlist.append([a,numlist[key]]) 

The contents of the new list: [['a', 3], ['b', 2], ['c', 1]]

+2
source
 p=[] for i in range(len(charlist)): p.append([charlist[i],numlist[i]]) 
+1
source

You can try the following, although I'm sure there will 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.

+1
source

Source: https://habr.com/ru/post/1346329/


All Articles