2

I have a list a:

a = ['2005', '2006']

and list b:

b = ['2005.123', '2005.234', '2006.123', '2007.234']

If I wanted a list of all the elements in b that contains a string '2005', I would do:

[value for value in b if '2005' in str(value)]

But I would like a list of all the values in b that contain either of the string values in list a (list a and b can be several elements long), and this one does not work:

[value for value in b if ['2005', '2006'] in str(value)]

I would like the code to return

['2005.123', '2005.234', '2006.123']

Is there an easier way to do this, without using loops?

0

2 Answers 2

4

Use any():

[value for value in b if any(d in value for d in a)]
#['2005.123', '2005.234', '2006.123']

Also, you do not have to call str(value) as it's already a string.


Update: Just for fun, here's another way to do the same thing using filter():

filter(lambda value: any(d in value for d in a), b)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you. The reason for str(value) was to allow for the chance that some numbers may not have been represented as string.
2

You ask for "contains" but your example has prefixes. If it's prefixes you want use str.startswith, which will allow you to pass a tuple of prefixes as its first argument:

a_tup = tuple(a)
[value for value in b if value.startswith(a_tup)]

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.