简体   繁体   English

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

[英]Permutations of a list split into two strings

Using the following list as an example : 以以下列表为例:

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

I can get all permutations using itertools.permutations 我可以使用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')]

But what if I need to get this output in the following format which is a list of lists containing all items split in two strings as follows: 但是,如果我需要以以下格式获取此输出,该格式是包含所有项目的列表列表,该项目分为两个字符串,如下所示:

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

This would provide the desired output from the initial question: 这将提供初始问题的期望输出:

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

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

Slicing input list and joining string can do a job for you. 切片输入列表和连接字符串可以为您完成工作。

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']]

You may use the below code to achieve this: 您可以使用以下代码实现此目的:

>>> 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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM