简体   繁体   中英

nested loop in list comprehension

I have a list of words in l that if any of it exists in the first index of each tuple in l2, remove the entire tuple.

my code:

l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]
l3 = [k for k in l2 if not any(i in k[0] for i in l) ]

somehow the code does not work and i get back an empty list for l3.

I want

l3 = [('looking for me', 'please hold')]

Split k[0] to get a list of words:

[k for k in l2 if not any(i in k[0].split() for i in l)]

This way it checks if i matches a word exactly.

It could also be interpreted as if k[0] does not starts with any of l , then you can do this:

[k for k in l2 if not k[0].startswith(tuple(l))]

Sets make membership testing easy. Use a function to filter your list.

import operator
first = operator.itemgetter(0

l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]

def foo(t, l = set(l)):
    t = set(first(t).split())
    return bool(l & t)

l3 = [thing for thing in l2 if not foo(thing)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM