列表的排列分为两个字符串

时间:2016-08-29 09:25:30

标签: python

使用以下列表作为示例:

a = ["cat", "dog", "mouse", "rat", "horse"]

我可以使用itertools.permutations

获取所有排列
print (list(itertools.permutations(a, 2)))

[('cat', 'dog'), ('cat', 'mouse'), ('cat', 'rat'), ('cat', 'horse'), ('dog', 'cat'), ('dog', 'mouse'), ('dog', 'rat'), ('dog', 'horse'), ('mouse', 'cat'), ('mouse', 'dog'), ('mouse', 'rat'), ('mouse', 'horse'), ('rat', 'cat'), ('rat', 'dog'), ('rat', 'mouse'), ('rat', 'horse'), ('horse', 'cat'), ('horse', 'dog'), ('horse', 'mouse'), ('horse', 'rat')]

但是,如果我需要以下列格式获取此输出,该列表包含分为两个字符串的所有项目的列表,如下所示:

[["cat", "dog mouse rat horse"], ["cat dog", "mouse rat horse"], ["cat dog mouse", "rat horse"], ["cat dog mouse rat", "horse"]]

3 个答案:

答案 0 :(得分:2)

这将提供初始问题所需的输出:

a = ["cat", "dog", "mouse", "rat", "horse"]

print[[" ".join(a[0:i]), " ".join(a[i:])] for i in range(1, len(a))]

答案 1 :(得分:1)

切片输入列表和加入字符串可以帮到你。

seq = ["cat", "dog", "mouse", "rat", "horse"]
seq2 = [[' '.join(seq[:i+1]), ' '.join(seq[i+1:])] for i in range(len(seq)-1)]
# [['cat', 'dog mouse rat horse'], ['cat dog', 'mouse rat horse'], ['cat dog mouse', 'rat horse'], ['cat dog mouse rat', 'horse']]

答案 2 :(得分:1)

您可以使用以下代码来实现此目的:

>>> a = ["cat", "dog", "mouse", "rat", "horse"]
>>> my_perm_list = []
>>> for i in range(len(a)-1):
...     my_perm_list.append((' '.join(a[:i+1]), ' '.join(a[i+1:])))
...
>>> my_perm_list
[('cat', 'dog mouse rat horse'), ('cat dog', 'mouse rat horse'), ('cat dog mouse', 'rat horse'), ('cat dog mouse rat', 'horse')]