[英]get all possible strings given multiple strings
I have multiple strings on different lines where I want to get all of the possible permutations without changing the order: 我在不同的行上有多个字符串,我希望在不更改顺序的情况下获得所有可能的排列:
for example: 例如:
er r er
er er r
which would give me: 这会给我:
er r er
er er r
er r r
er er er
Is there a way to do this is python? 有没有办法做到这一点的python? If this is a duplicate please advise but I was not able to find one.
如果这是重复的,请告知,但我找不到。
This is different from questions like Finding all possible permutations of a given string in python where only one string is used 这与诸如在仅使用一个字符串的python中查找给定字符串的所有可能排列之类的问题不同
Update [Still does not work] 更新[仍然无效]
import itertools
with open(in_file) as f:
lis = list(f)
print (lis)
print([' '.join(x) for x in itertools.product(*map(set, zip(*map(str.split, lis))))])
[Error] [错误]
[['er', 'r', 'er'], ['er', 'er', 'r']]
Traceback (most recent call last):
File "test.py", line 37, in <module>
print([' '.join(x) for x in itertools.product(*map(set, zip(*map(str.split, S))))])
TypeError: descriptor 'split' requires a 'str' object but received a 'list'
You can zip
the splits of these strings and take the cartesion product
, eg: 您可以
zip
这些字符串的拆分并采用笛卡尔product
,例如:
>>> import itertools as it
>>> s1, s2 = 'er r er', 'er er r'
>>> {' '.join(x) for x in it.product(*zip(s1.split(), s2.split()))}
{'er er er', 'er er r', 'er r er', 'er r r'}
You can get duplicates so, constructed as a set
comprehension. 因此,您可以获取副本,将其构造为
set
理解。
Updated for an arbitrary number of strings: 更新了任意数量的字符串:
>>> import itertools as it
>>> ss = ['er r er', 'er er r', 'ar er r']
>>> {' '.join(x) for x in it.product(*zip(*map(str.split, ss)))}
{'ar er er', 'ar er r', 'ar r er', 'ar r r', 'er er er', 'er er r', 'er r er', 'er r r'}
Note: You could also apply the set
to the arguments to product
to remove duplicates and it might be quicker depending on the overlaps of the strings, eg: 注意:您也可以将
set
应用于product
的参数以删除重复项,这取决于字符串的重叠情况可能更快,例如:
>>> [' '.join(x) for x in it.product(*map(set, zip(*map(str.split, ss))))]
['er r r', 'er r er', 'er er r', 'er er er', 'ar r r', 'ar r er', 'ar er r', 'ar er er']
To read from a file type object: 要从文件类型对象读取:
>>> with open(in_file) as f:
... lis = list(f)
>>> print([' '.join(x) for x in it.product(*map(set, zip(*map(str.split, lis))))])
['er r r', 'er r er', 'er er r', 'er er er']
Or more compactly: 或更紧凑:
>>> with open(in_file) as f:
... print([' '.join(x) for x in it.product(*map(set, zip(*map(str.split, f))))])
['er r r', 'er r er', 'er er r', 'er er er']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.