列表理解 - 使用每个元素两次

Lon*_*Rob -1 python

我有两个列表如下:

first = [1, 2, 3] # integers
second = ["A", "B"]
Run Code Online (Sandbox Code Playgroud)

我想生成以下列表,交替A和B.请注意,生成的iterable比输入的iterables长:

["1A", "1B", "2A", "2B", "3A", "3B"]
Run Code Online (Sandbox Code Playgroud)

我目前正在使用itertools:

[str(x1) + x2 for x1, x2 in itertools.product(first, second)]
Run Code Online (Sandbox Code Playgroud)

但这是"最好的"方式吗?有没有需要导入的解决方案?

Aro*_*unt 5

你可以试试

>>> first = [1, 2, 3]
>>> second = ['A', 'B']
>>> ["{}{}".format(f, s) for s in second for f in first]
['1A', '2A', '3A', '1B', '2B', '3B']
Run Code Online (Sandbox Code Playgroud)

  • 我只是为了可伸缩性而使用`itertools.product`:`print(["{} {}".格式(f,s)为f,s在产品中(第一,第二)]) (2认同)