在下列情况下如何从A和B获得C?

时间:2013-12-03 20:02:54

标签: python list

如果在下列情况下从A和B获得C?

A = ['5','6','7','8']
B = ['1','2','3','4']

C = [['5','1'],['6','2'],['7','3'],['8','4']]

3 个答案:

答案 0 :(得分:2)

使用zip:http://docs.python.org/2/library/functions.html#zip

In [1]: A = [5,6,7,8]

In [2]: B = [1,2,3,4]

In [3]: zip(A,B)
Out[3]: [(5, 1), (6, 2), (7, 3), (8, 4)]

In [4]: map(list, zip(A, B))
Out[4]: [[5, 1], [6, 2], [7, 3], [8, 4]]

In [5]: [list(x) for x in  zip(A, B)]
Out[5]: [[5, 1], [6, 2], [7, 3], [8, 4]]

编辑:在[4]到[5]

中添加

答案 1 :(得分:1)

像这样:

>>> [list(t) for t in zip(A, B)]
[['5', '1'], ['6', '2'], ['7', '3'], ['8', '4']]

如果您执行简单:zip(A, B),那么您将获得一个元组列表,这不是您要求的严格内容:

>>> zip(A, B)
[('5', '1'), ('6', '2'), ('7', '3'), ('8', '4')]

然后将list()应用于zip出来的每个元组,以获得您所要求的内容。

答案 2 :(得分:1)

zip使用map或列表理解:

>>> map(list, zip(A, B))
[['5', '1'], ['6', '2'], ['7', '3'], ['8', '4']]
>>> [list(x) for x in  zip(A, B)]
[['5', '1'], ['6', '2'], ['7', '3'], ['8', '4']]