如何在Python3中将两个列表的str.join组合成字符串?

时间:2019-05-27 08:13:55

标签: python python-3.x list

我想获取('A_1','A_2','B_1','B_2','C_1','C_2')的列表,其中包含'_'.join()[(x, y) for x in ['A','B','C'] for y in [1,2]]之类的东西。

该怎么写?

1 个答案:

答案 0 :(得分:3)

使用itertools.product

python3.6+

import itertools
letters = ['A','B','C']
nums = [1, 2]
result = [f"{l}_{n}" for l, n in itertools.product(letters, nums)]

或在较低的python版本中:

result = ["{}_{}".format(l, n) for l, n in itertools.product(letters, nums)]

输出:

>>> result
['A_1', 'A_2', 'B_1', 'B_2', 'C_1', 'C_2']