我们假设我有两个列表:
list_one = [1A, 1B]
list_two = [2A]
如何从这两个数组中获取包含单词对的列表?想象:
answer = [1A-2A, 1B-2A]
我知道我可以使用两个for
循环来实现它但是有一种'pythonic'方式吗?
答案 0 :(得分:7)
您只需使用product
from itertools
。
from itertools import product
list_one = ['1A', '1B']
list_two = ['2A']
result = ['-'.join(sub) for sub in product(list_one, list_two)]
print(result) # -> ['1A-2A', '1B-2A']
我不认为它会比 pythonic 更多。
在幕后,product(list_one, list_two)
生成('1A', '2A')
格式的元组,我们只需'-'.join()
即可生成所需的结果。