2

I have a list:

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

I want to check the condition below against the list above

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

How can I convert the condition above in regex?

Right now I am checking this in a loop and I think regex would be a better option maybe?

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
3
  • What is the goal of that for cycle? it always returns the weighted_views result of the last list element right now. Commented Dec 18, 2015 at 11:50
  • 1
    Are you confusing continue with break? Continue just does the next iteration, which it would do anyway. Also you could avoid calling el.split('|') twice. I know it's only example code, but still worth noting. Commented Dec 18, 2015 at 11:51
  • you're right, I am confusing it! Commented Dec 18, 2015 at 11:54

2 Answers 2

1

Since the strings look like a sort of CSV, I would prefer to work with split function and completely avoid regex.

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
Sign up to request clarification or add additional context in comments.

Comments

1

if regular expressions certainly make life easier

I hope this works for you

import re

x = [

u'x|frequency|x:y|||cbase',
u'x|frequency|x:y||weights_UK18|cbase',
u'x|frequency||y|weights_UK18|c%'

]

t = "-".join(x)+'-'

x = re.findall(r'((?:x\|\w+\|(?:x:y)?\|)(?!\|)[^-]*)+', t)

where x is your new list already filtered

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.