1

I've the following list:

my_list = ['a', 'b', 'c']

I've the following list of strings:

my_strings = ['azz', 'bzz', 'czz']

I'm doing the following to determine if any items of my_list are in contained within a item in my_strings:

for my_string in my_strings:
    if any(x in my_string for x in my_list):
        # Do Stuff

What's the best practice for retaining the x as found in my_list so that I might be able to then do the following:

#Do Stuff
new_var = my_string.split('x')[1]

The desired result would be able to assign zz to new_var by determining that a from my list was in azz from my_strings

alphazwest
  • 3,483
  • 1
  • 27
  • 39
  • Please provide an example of your expected result, your last sentences are not clear to me ;) – RaphaMex Jul 08 '17 at 18:18
  • https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method check here – BENY Jul 08 '17 at 18:21
  • @wen That's the end logic, but I'm trying to retain the `'blah'` to be able to check. Right now, using the `any()` function doesn't let me know which element was found to make that check, right? – alphazwest Jul 08 '17 at 18:25

4 Answers4

2

It is simple indeed, you can even do it in a beautiful one liner using list comprehension as follows:

new_var = [my_string.split(x)[1] for my_string in my_strings for x in my_list if x in my_string]

this returns for you 2nd element from all splits of all strings in my_strings in which there exists elements from my_list

Rayhane Mama
  • 2,374
  • 11
  • 20
  • 1
    That's great! That did away with my whole function, and returned the values as I was attempting. Thank you – alphazwest Jul 08 '17 at 18:35
0

You should not use any because you actually care about which one matches:

for my_string in my_strings:
    for x in my_list:
        if x in my_string:
            #Do Stuff
            my_string.split('x')[0]
            break
RaphaMex
  • 2,781
  • 1
  • 14
  • 30
0

You should not use any() because you need to know specifically which element matches a certain string. Simply use a regular for loop instead:

>>> def split(strings, lst):
...     for string in strings:
...         for el in lst:
...             if el in string:
...                 yield string.split(el)[1]
... 
>>> 
>>> for string in split(['azz', 'bzz', 'czz'], ['a', 'b', 'c']):
...     print(string)
... 
zz
zz
zz
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

Let's say if you want to split first value of my_string with first value of my_list

my_string[0].split(my_list[0])
BENY
  • 317,841
  • 20
  • 164
  • 234