How do i match list with another list in python

Viewed 159

I want to find first list value to another list value in python, where i used match and set and findall other method too but it's not work well in my code.

Here I want to match that pattern is in the longlist and pattern always startwith.

pattern  = ['aaa','bbbb','ccc']
longlist = ['aaa845','bbbbPP44','XXX10','aaa420','ccc1','jjj7000','PPPP'] 

for i in longlist:  # longlist is json data, So this line required. After we can do it any code
  if filter(pattern.match, i): 
    print(i)

  # other tried
  if set(pattern) & set(longlist):
    print(i)

Desire output : aaa845, bbbbPP44, aaa420, ccc1

Can anyone suggest best coding style without multiple FOR loop iteration and fastest performance ?

1 Answers

You can use a list comprehension with any that short circuits the inner loop if a match is found.

This checks if any of the word in pattern is "contained" in the words of longlist.

>>> pattern  = ['aaa','bbbb','ccc']
>>> longlist = ['aaa845','bbbbPP44','XXX10','aaa420','ccc1','jjj7000','PPPP']
>>> [i for i in longlist if any(j in i for j in pattern)]
['aaa845', 'bbbbPP44', 'aaa420', 'ccc1']

If instead you want the words in longlist to "start with" any of the ones in pattern then you need to change the condition like so.

>>> [i for i in longlist if any(i.startswith(j) for j in pattern)]
['aaa845', 'bbbbPP44', 'aaa420', 'ccc1']

In your given example both happen to yield the same result.

Related