Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于条件匹配和重构Python中的一对字符串_Python_String_Python 3.x_List_Pattern Matching - Fatal编程技术网

基于条件匹配和重构Python中的一对字符串

基于条件匹配和重构Python中的一对字符串,python,string,python-3.x,list,pattern-matching,Python,String,Python 3.x,List,Pattern Matching,我在Python3.x中有以下一对短字符串,其长度必须相等: string_a = 'he_lo_world' string_b = 'hi_low_oldd' 考虑到以下规则,我希望根据配对中的字符如何匹配,尽快创建一个“摘要字符串”: (1) 如果字符相同,则新字母为S(相同)。除非匹配的字符是\uu,否则它就是U(下划线) (2) 否则,字符不匹配。如果不匹配,则字母为N(不匹配)。如果string\u a有\u而string\u b没有,则它是a。如果string\u b有\u而str

我在Python3.x中有以下一对短字符串,其长度必须相等:

string_a = 'he_lo_world'
string_b = 'hi_low_oldd'
考虑到以下规则,我希望根据配对中的字符如何匹配,尽快创建一个“摘要字符串”:

(1) 如果字符相同,则新字母为S(相同)。除非匹配的字符是
\uu
,否则它就是U(下划线)

(2) 否则,字符不匹配。如果不匹配,则字母为N(不匹配)。如果
string\u a
\u
string\u b
没有,则它是
a
。如果
string\u b
\u
string\u a
没有,则为
b

对于上面的一对,字符串应为:

SNUSSABSNNS
为了构造这个字符串,我认为多个if/for语句效率太低

这里使用列表理解和itertools示例

我可以得到匹配的索引。(在列表理解中,
\u==\ u
异常需要一个条件,因此上面不应该存在索引2。)


我很困惑(A)如何根据索引列表重新构造字符串,以及(B)如何有效地处理不匹配的字符

您可以使用
zip

string_a = 'he_lo_world'
string_b = 'hi_low_oldd'
new_s = ''.join(['S', 'U'][a == '_'] if a == b else 'N' if a != '_' and b != '_' else ['A', 'B'][b == '_' and a != '_'] for a, b in zip(string_a, string_b))
输出:

'SNUSSABSNNS'

您可以使用
zip

string_a = 'he_lo_world'
string_b = 'hi_low_oldd'
new_s = ''.join(['S', 'U'][a == '_'] if a == b else 'N' if a != '_' and b != '_' else ['A', 'B'][b == '_' and a != '_'] for a, b in zip(string_a, string_b))
输出:

'SNUSSABSNNS'