Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

python - Check if one item in a list is in a list of lists

Let's say I have a list of lists, e.g:

my_list = [['ab', 'bc'], ['cd', 'de'], ['ef', 'fg'], ['gh', 'hi']]

I then have a list of no-go words, e.g:

no_go_list = ['ab', 'fg']

What I would like to do is to get a list, where it checks if at least one of the items in the no_go_list is in one of the lists in my_list, so the result should just be:

final_list = [['cd', 'de'], ['gh', 'hi']]

I was thinking about doing it like this:

final_list = [l for l in my_list if not no_go_list in l]

But this checks if both of the no_go_list items present. So I am guessing this needs some modification, I just can't seem to figure out how.

question from:https://stackoverflow.com/questions/65894275/check-if-one-item-in-a-list-is-in-a-list-of-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check whether any item in no_go_list is in the element. Thus, the "obvious" way is to use the any function.

final_list = [l for l in my_list 
                if not any(word in l for word in no_go_list)]

Your posted code does not check for both of the items being present: it checks to see whether that list value is present. You would need something like

my_list = [[['ab', 'fg'], 'bc'], ['cd', 'de'], 
            ['ef', ['ab', 'fg']], ['gh', 'hi']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...