我正在研究类的分配,我正在使用正则表达式返回指定字符串中所有模式匹配的位置。如果有匹配项,我将返回索引,如果找不到匹配项,我需要返回。我已经成功地完成了此操作,但想将整个表达式放入一行,就像我在评论的返回语句中所做的那样。
def searchMotif(sequence, motif):
if not type(motif) is str:
raise Exception("Invalid Motif")
#matches = re.finditer(motif, sequence)
#indices = [(match.start(), match.end()) for match in matches]
indices = [(match.start(), match.end()) for match in re.finditer(motif, sequence)]
if indices:
return indices
else:
return None
#return [(match.start(), match.end()) for match in matches]
#return [(match.start(), match.end()) for match in re.finditer(motif, sequence)]
理想情况下,我想有一个与 return [(match.start(), match.end() for match in re.finditer(motif, sequence)] else None
。我知道这种语法是不正确的,但我希望它能跨越我要实现的目标。我是正则表达式和列表理解的新手,因此我不确定您是否可以在我的列表中使用IF语句。
是否可以通过正则迭代器填充列表并在返回语句中检查它是否为空?
使用:
def test():
return [] or None
print(test())
输出:
None
原因是,任何空的迭代(设置,dict,list,string,...(都被视为 False
对于您的代码:
return indices or None # no if indices: needed
读数:https://docs.python.org/3/library/stdtypes.html#truth-value-testing
[...]大多数内置对象被认为是错误的:
- 常数定义为错误:无和错误。
- 任何数字类型的零:0、0.0、0J,十进制(0(,分数(0,1(
- 空序列和集合:'',((,[],{},set((,range(0(
[...]