如何使用List comprehension获得所需的结果

时间:2013-12-31 09:32:03

标签: python list

我有两个清单

A=['A','B']
B=['C','D']

我想将其显示为

[['AC','BC'],['AD','BD']]

任何帮助?

2 个答案:

答案 0 :(得分:4)

[[internal+external for internal in A] for external in B]

答案 1 :(得分:0)

您可以使用itertools.product然后itertools.groupby

>>> from itertools import product, groupby
>>> x = ['a','b']
>>> y = ['c','d']
# Group by first char
>>> [list(g) for k, g in groupby([i+j for i,j in product(x,y)], key=lambda x: x[0])]
[['ac', 'ad'], ['bc', 'bd']]
# Group by last char
>>> [list(g) for k,g in groupby(sorted([i+j for i,j in product(x,y)], key=lambda x:x[-1]), key=lambda x:x[-1])]
[['ac', 'bc'], ['ad', 'bd']]