我有两个列表['_ru', '_uk', '_en'], ['1','2','3']
我如何获得
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']
在一行?
答案 0 :(得分:5)
您可以使用itertools.product
获取两个列表的笛卡尔积并加入它们,就像这样
>>> l2, l1 = ['_ru', '_uk', '_en'], ['1','2','3']
>>> from itertools import product
>>> ["".join(items) for items in product(l1, l2)]
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']
或者在一行中,列表理解
>>> ["{}{}".format(i1, i2) for i1 in l1 for i2 in l2]
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']
这与迭代第一个列表中每个项目的第二个列表并累积结果基本相同,如下所示
>>> result = []
>>> for i1 in l1:
... for i2 in l2:
... result.append("{}{}".format(i1, i2))
>>> result
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']