简体   繁体   English

生成可变序列长度的列表排列

[英]Generating List Permutations of Variable Sequence Lenghts

Suppose I have a list that looks like this: 假设我有一个看起来像这样的列表:

beast = ['E', 'O', 'R', 'E', 'O', 'S', 'P', 'E', 'P', 'P', 'O', 'R', 'S', 'P', 'O', 'E']

Now, here are the basic patterns that I want to extract: 现在,这是我要提取的基本模式:

basic_oros = ['O', 'R', 'O']

pi_poro = ['P', 'O', 'R', 'O']

pi_orpo = ['O', 'R', 'P', 'O']

pi_porpo = ['P', 'O', 'R', 'P', 'O']

si_orso = ['O', 'R', 'S', 'O']

spi_orspo = ['O', 'R', 'S', 'P', 'O']

spi_porso = ['P', 'O', 'R', 'S', 'O']

spi_porspo = ['P', 'O', 'R', 'S', 'P', 'O']

The problem is, if I extract only ['P', 'O', 'R', 'S', 'P', 'O'] out of beast , I miss out on the previous P before that pattern occurs. 问题是,如果我只从beast提取['P', 'O', 'R', 'S', 'P', 'O'] ,那么在出现该模式之前,我会错过先前的P

(Better example - There can also be ['O', 'O', 'R', 'O', 'O', 'O'] ) (更好的例子-也可以有['O', 'O', 'R', 'O', 'O', 'O']

Therefore, every letter in those basic patterns can be expanded in a sense of: 因此,可以从以下意义上扩展这些基本模式中的每个字母:

Os can occur together thrice. Os可以一起发生三次。

Ps can occur together twice. PS可以一起出现两次。

Rs can occur together twice. Rs可以一起出现两次。

Ss can occur only once. SS只能出现一次。

I want to generate a list of all possible permutations but have no idea where to start. 我想生成所有可能排列的列表,但不知道从哪里开始。

I wrote a naive python code that replaces every occurrence of O with three Os and etc. But that results in - 我写了一个朴素的python代码,用三个O等替换了每次出现的O,但是结果是-

['O', 'O', 'O', 'R' 'O', 'O', 'O']

Which won't work when I need to find: ['O', 'R', 'O', 'O'] 当我需要查找以下内容时,该方法将不起作用: ['O', 'R', 'O', 'O']

Any help is appreciated. 任何帮助表示赞赏。 Thank you. 谢谢。

This sounds like a job for regexes. 这听起来像是正则表达式的工作。 If you join your beast list into a string with ''.join(beast) , you can build regexes to search it for substrings matching specific patterns. 如果您将beast列表加入到带有''.join(beast)的字符串中,则可以构建正则表达式来搜索与特定模式匹配的子字符串。 For example, using the {m,n} quantifier to search for a certain number of repetitions of a subpattern, you can use 例如,使用{m,n}量词搜索子模式的一定重复次数,可以使用

re.search(r'O{1,3}R{1,2}O{1,3}', ''.join(beast))

to search for a pattern consisting of 1 to 3 Os, 1 to 2 Rs, and 1 to 3 more Os. 搜索由1至3个Os,1至2个Rs和另外1至3个Os组成的模式。

See the re module documentation for more information on Python's regex syntax and functions, and see any number of online tutorials for help getting used to writing regexes. 有关Python的regex语法和函数的更多信息,请参见re模块文档 ,并参阅许多在线教程以获取习惯于编写regexes的帮助。

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

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