0

Say I have a list match = ['one', 'two', 'three']

and I have a list of arguments foo = ['something', 'something_two', 'something', (...)]

I want to only do an operation on the item if it matches any of the items in the match list:

for each in foo:
    for match_item in match:
        if match_item not in each:
            no_match = True
            break
    if no_match:
        break
    # do the desired operations

But I don't know how to make it so that it doesn't fail the match when 'something_two' comes up against 'one' and breaks all of the loops. The items in match will be only a part of the whole string in the items of foo, that's why I was looping through the list of items in match.

What would be a good way of approaching this?

1
  • Can't you just do if each in match: # do desired op ? Commented Aug 12, 2016 at 18:22

2 Answers 2

1

The simplest way I can think of is

for item in foo:
    if item in match:
        # do desired operations

or if you want to do the operations on the list itself

for i in range(len(foo)):
    if foo[i] in match:
        # do desired operation on foo[i]
Sign up to request clarification or add additional context in comments.

Comments

1

You can reduce the list by using a generator expression with a condition:

for each in (item for item in foo if item in match):
    # do the desired operations

or by using filter function:

for each in filter(lambda item: item in match, foo):
    # do the desired operations

1 Comment

Will the first method work if item contains more characters than the ones in match[0] ? say that each = 'something_one' and match is only 'one' I can't seem to make it work

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.