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
220 views
in Technique[技术] by (71.8m points)

python - Perform partial one list items match into another with a catch

I have two list :

list_1 = ['world', 'abc', 'bcd', 'ghy', 'car', 'hell', 'rock']
list_2 = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']

I would like to check if words of list_1 exists in list_2 in any shape or form and simple delete that whole sentence from list_2 and finally, print list_2

For example:

the word 'world' from list_1 should take out the sentence 'the world is big' from list_2
the word 'car' from list_2 should take out the sentence 'i want a car'

I have tried using list comprehension like this, but it sadly repeats

output = [j for i in list_1 for j in list_2 if i not in j]

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

1 Reply

0 votes
by (71.8m points)

You should consider giving meaningfull names to your variable when you can, this helps you writing your code

What you want is

  • iterate over the sentences
  • for each check that no word from list_1 is in it
output = [sentence for sentence in list_2
          if all(word not in sentence for word in list_1)]

print(output)  # ['puppies are best']

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

...