使用python中的列表中的元素创建所有无序对的情况

时间:2019-04-29 05:39:30

标签: python-3.7

我有一个列表:

a_list = ["apple", "pear", "grape", "soil"]

我想要元素和无序对:

["apple", "apple pear", "apple grape", "apple soil", "pear", "pear grape", "pear soil", "grape", "grape soil", "soil"]

1 个答案:

答案 0 :(得分:1)

这是使用itertools.combinations的选项:

from itertools import combinations

a_list = ["apple", "pear", "grape", "soil"]
res = a_list + list(" ".join(comb) for comb in combinations(a_list, 2))
# ['apple', 'pear', 'grape', 'soil', 'apple pear', 'apple grape', 'apple soil',
#  'pear grape', 'pear soil', 'grape soil']