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?

DPdl
  • 723
  • 7
  • 23

2 Answers2

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)
pault
  • 41,343
  • 15
  • 107
  • 149
  • Perfect! Thank you. The reason for str(value) was to allow for the chance that some numbers may not have been represented as string. – DPdl Mar 08 '18 at 22:22
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)]
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119