简体   繁体   English

这个python表达式中%的含义是什么

[英]What is the meaning of % in this python expression

Can someone explain what this regular expression means? 有人可以解释这个正则表达式的含义吗? I am looking at someone else's python code, and I just find myself curious as to what the expression is doing. 我正在看别人的python代码,我只是对表达式的作用感到好奇。 I am also not certain what the 2nd % sign means. 我也不确定第二个%符号的含义。

regexStr = '(%s)' % '|'.join(['.*'.join(str(i) for i in p) for p in itertools.permutations(charList)])

So it does this: 这样做:

import itertools
charList = [1, 2, 3]

'(%s)' % '|'.join(['.*'.join(str(i) for i in p) for p in itertools.permutations(charList)])
#>>> '(1.*2.*3|1.*3.*2|2.*1.*3|2.*3.*1|3.*1.*2|3.*2.*1)'

First it generates all of the permutations of the input (unique orders): 首先,它生成输入的所有排列(唯一顺序):

for permutation in itertools.permutations(charList):
    print(permutation)
#>>> (1, 2, 3)
#>>> (1, 3, 2)
#>>> (2, 1, 3)
#>>> (2, 3, 1)
#>>> (3, 1, 2)
#>>> (3, 2, 1)

For each of these, it converts each item to a string and joins them with .* 对于其中的每个,它将每个项目转换为字符串,然后将它们与.*连接起来.*

'.*'.join(str(i) for i in (1, 2, 3))
#>>> '1.*2.*3'

Then it joins all of those with | 然后将所有这些|

'|'.join(['.*'.join(str(i) for i in p) for p in itertools.permutations(charList)])
#>>> '1.*2.*3|1.*3.*2|2.*1.*3|2.*3.*1|3.*1.*2|3.*2.*1'

and finally uses '(%s)' % result to wrap the result in brackets : 最后使用'(%s)' % result'(%s)' % result 包装在方括号中

'(%s)' % '|'.join(['.*'.join(str(i) for i in p) for p in itertools.permutations(charList)])
#>>> '(1.*2.*3|1.*3.*2|2.*1.*3|2.*3.*1|3.*1.*2|3.*2.*1)'

The pattern '1.*2.*3' matches all sequences like 111111222333333 . 模式'1.*2.*3'匹配所有序列,如111111222333333

The patern A|B|C|D matches one of A , B , C or D . 的百通A|B|C|D匹配的一个 ABCD

So the resulting regex matches any permutation, with each item repeated any number of times (including 0). 因此,生成的正则表达式匹配所有排列,每个项目重复任意次数(包括0)。

The outer brackets make this a capturing group. 外括号使它成为一个捕获组。

Just try it with a test string. 只需尝试使用测试字符串即可。 Let's try 'abc' 让我们尝试“ abc”

regexStr = '(%s)' % '|'.join(['.*'.join(str(i) for i in p) for p in itertools.permutations('abc')])

>>> regexStr
'(a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a)'

So it creates a regex search string, with each character of the permeated passed in string delimited by '.*' and each of the permutations delimeted by '|' 因此,它创建了一个regex搜索字符串,其中渗透字符串的每个字符以'.*'分隔,并以'|'分隔每个排列'|' .

If any of the steps within that line of code confuse you, look at the documentation for each component 如果该代码行中的任何步骤使您感到困惑,请查看每个组件的文档

itertools.permutations
str.join
regex formatting

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

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