11

I would like to merge two lists into one 2d list.

list1=["Peter", "Mark", "John"]
list2=[1,2,3]

into

list3=[["Peter",1],["Mark",2],["John",3]]
4

3 回答 3

26
list3 = [list(a) for a in zip(list1, list2)]
于 2012-09-27T15:14:23.990 回答
3

An alternative:

>>> map(list,zip(list1,list2))
[['Peter', 1], ['Mark', 2], ['John', 3]]

or in python3:

>>> list(map(list,zip(list1,list2)))
[['Peter', 1], ['Mark', 2], ['John', 3]]

(you can omit the outer list()-cast in most circumstances, though)

于 2012-09-27T15:20:20.317 回答
0

I actually used:

list3a = np.concatenate((list1, list2))
list3 = np.reshape(list3a, (-1,2))

because otherwise I get the error: 'list indices must be integers, not tuples' when trying to reference the array.

于 2015-03-12T12:36:49.260 回答