Skip to main content
 首页 » 编程设计

python 正则表达式在列表中查找匹配项

2024年10月24日46lonelyxmas

我有一个列表:

chain_views = [u'x|frequency|x:y|||cbase',  
               u'x|frequency|x:y||weights_UK18|cbase',  
               u'x|frequency||y|weights_UK18|c%'] 

我想根据上面的列表检查下面的条件

if el.startswith('x|frequency|') and el.split('|')[4]!='' and el.split('|')[3]=='y': 

如何在正则表达式中转换上述条件?

现在我正在循环检查它,我认为正则表达式可能是更好的选择?

for el in chain.views: 
 
    if el.startswith('x|frequency|') and el.split('|')[4]!='' and el.split('|')[3]=='y': 
        weighted_views = True 
        break 
    else: 
        weighted_views = False 
 
return weighted_views 

请您参考如下方法:

由于字符串看起来像一种 CSV,我更愿意使用 split 函数并完全避免正则表达式。

for el in chain_views: 
    a0, a1, a2, a3, a4, a5 = el.split('|')  # give better names 
    if a0 == 'x' and a1 == 'frequency' and a3 == 'y' and a4: 
        return True 
return False