Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-list comprehension in Python

Let's say I have two lists of strings:

a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']

where #### represents 4-digit random number. And

b = ['boo', 'aaa', 'bii']

I need to know which string entry in list a contains any given entry in b. I was able to accomplish this by couple of nested loops and then using the in operator for checking the string contains the current entry in b. But, being relatively new to py, I'm almost positive this was not the most pythonic or elegant way to write it. So, is there such idiom to reduce my solution?

like image 830
rdodev Avatar asked Jul 28 '26 03:07

rdodev


1 Answers

The following code gives you an array with the indexes of a where the part after the slash is an element from b.

a_sep = [x.split('/')[1] for x in a]
idxs = [i for i, x in enumerate(a_sep) if x in b]

To improve performance, make b a set instead of a list.

Demo:

>>> a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']
>>> b = ['boo', 'aaa', 'bii']
>>> a_sep = [x.split('/')[1] for x in a]
>>> idxs = [i for i, x in enumerate(a_sep) if x in b]
>>> idxs
[0, 3]
>>> [a[i] for i in idxs]
['####/boo', '####/bii']

If you prefer to get the elements directly instead of the indexes:

>>> a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']
>>> b = ['boo', 'aaa', 'bii']
>>> [x for x in a if x.split('/')[1] in b]
['####/boo', '####/bii']
like image 52
ThiefMaster Avatar answered Jul 29 '26 16:07

ThiefMaster