0

I try to find some string in a list, but have problems because of word order.

list = ['a b c d', 'e f g', 'h i j k']
str = 'e g'

I need to find the 2nd item in a list and output it.

D3IGER
  • 15
  • 2

4 Answers4

0

You can try:

for l in list:
     l_words = l.split(" ")
     if all([x in l_words for x in str.split(" ")]):
         print(l_words)
akhavro
  • 101
  • 7
0

You can try this

list = ['a b c d', 'e f g', 'h i j k']
str = list[2].split()
for letter in str:
  print(letter)
0

This can be achieved by using sets and list comprehension

ls = ['a b c d', 'e f g', 'h i j k']
s = 'e g'
print([i for i in ls if len(set(s.replace(" ", "")).intersection(set(i.replace(" ", "")))) == len(s.replace(" ", ""))])

OR

ls = ['a b c d', 'e f g', 'h i j k']
s = 'e g'
s_set = set(s.replace(" ", ""))
print([i for i in ls if len(s_set.intersection(set(i.replace(" ", "")))) == len(s_set)])

Output

['e f g']

The list comprehension is removing all the items in ls that all the chars from s are not including inside the list item, by that you will get all the ls items that all the s chars are in them.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

You can use combination of any() and all() to check the presence in one line:

>>> my_list = ['a b c d', 'e f g', 'h i j k']
>>> my_str = 'e g'

>>> any(all(s in sub_list for s in my_str.split()) for sub_list in my_list)
True

Here, above expression will return True / False depending on whether the char in your strings are present inside the list.

To also get the get that sub-list as return value, you can modify above expression by skipping any() with list comprehension as:

>>> [sub_list for sub_list in my_list if all(s in sub_list for s in my_str.split())]
['e f g'] 

It'll return the list of strings containing your chars.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Thank you very much! Will this work with words instead of characters(in string)? – D3IGER Jan 17 '21 at 14:59
  • 1
    It'll work but upto certain extent, it won't be doing exact word match. For example: check for `"est"` in `"test string"` will return `True`. If you are looking for exact match of word, then it'll be better fit as a separate question. Logic of word lookup will be little different that char lookup we have here – Moinuddin Quadri Jan 17 '21 at 15:10