2015-11-13 34 views
1

我有一个列表,它看起来像这样:如果x是列表与正则表达式

mylist = [ 
      u'x|freq|x:y|||cbase', 
      u'x|freq|x:y||weights_UK18|c%', 
      u'x|freq||y|weights_UK18|c%', 
      u'x|mean|x[0,0.25]:y||weights|JFP', 
      u'x|median|x[0]:y||weights_UK18|JFP_q1' 
      ] 

我想基于两个条件

1. if the item startswith('x|frequency||y|') 
2. and if something exists in between the 4th and 5th "|" 

现在我在做这个找项目一个循环:

for item in mylist: 
    vkey = v.split('|') 
    weight = vkey[4] 
    if v.startswith('x|frequency||y|') and weight!='': 
     chart_data_type = 'weighted' 

但是有没有办法可以在一条线上做到这一点?

if this in mylist: 
     #blah blah 

回答

1

,你可以使自己的发电机,即

def G(L): 
    for item in L: 
     vkey = item.split('|') 
     weight = vkey[4] 
     if item.startswith('x|frequency||y|') and weight!='': 
      yield item 

for item in G(mylist): 
    print(item) 

或使用列表理解(假设输入是有效的,因此[4]不会产生异常),例如,

for item in [el for el in mylist if el.startswith('x|frequency||y|') and el.split('|')[4]!='']: 
    print(item) 
+0

谢谢!决定去简单的列表理解 –

1

您可以对此使用正则表达式:

import re 
for item in mylist: 
    if re.match('x\|frequency\|\|y\|[^|]+\|', item): 
     chart_data_type = 'weighted' 

但由于x|frequency||y|是一个静态文本,并谈到直接前要检查的第四部分,你可以只检查字符串快得多做到这一点:

prefix = 'x|frequency||y|' 
for item in mylist: 
    if item.startswith(prefix) and item[len(prefix)] != '|': 
     chart_data_type = 'weighted' 

这基本上检查,如果在前缀后面的字符是|,在这种情况下,您知道没有值。

+0

感谢您的努力 - upvote! –

1

如果你坚持在同一行的解决方案:

any(map(lambda i: i.startswith('x|freq||y|') and i.split('|')[4] != '', mylist)) 

上面一行将返回True如果你的名单上有至少1项满足条件i.startswith('x|freq||y|') and i.split('|')[4] != ''

说明:

  1. lambda i: i.startswith('x|freq||y|') and i.split('|')[4] != ''

是一个内联函数,用于检查您的条件。我认为你很清楚我们如何做检查。

  1. map函数用于通过使用上述lambda函数处理列表中的每个项目来创建结果列表。通常你会传递一个函数的名字作为第一个参数,但我使用lambda(内联函数)来保持它更简单。其结果将是这样的:

    [假,假,真,假,假]

  2. any如果给列表中包含至少1 True项目将返回true。

+0

感谢您的努力 - upvote! –