[英]Find matching words and not matching words in a list and a list
我是学习 Python 的初学者,我有两个列表
list1 = ['product','document','light','time','run']
list2 = ['survival','shop','document','run']
我想找到匹配的单词而不是匹配的单词
这是示例结果
matching_words = ['document','run']
notmatching_words = ['product','light','time','survival','shop']
我能怎么做
尝试:
matching_words = []
notmatching_words = list(list2) # copying the list2
for i in list1:
if i in list2:
matching_words.append(i) # appending the match
notmatching_words.remove(i) # removing the match
else:
notmatching_words.append(i) # appending the un-matched
这给出了:
>>> matching_words
['document', 'run']
>>> notmatching_words
['survival', 'shop', 'product', 'light', 'time']
或者您可以使用集合匹配:
matching_words = list (set(list1) & set(list2)) # finds elements existing in both the sets
notmatching_words = list(set(list1) ^ set(list2))
已回答的解决方案效果很好,但我想提出另一个使用set
数据结构的解决方案,因为这是最适合此类问题的解决方案:
list1 = ['product','document','light','time','run']
list2 = ['survival','shop','document','run']
set1 = set(list1)
set2 = set(list2)
matching_words = set1.intersection(set2)
# {'document', 'run'}
nonmatching_words = set1.symmetric_difference(set2)
# {'time', 'light', 'shop', 'survival', 'product'}
请注意,元素的顺序是随机的。
但是,如果顺序不重要,您甚至可能希望从头到尾使用集合:
# DECLARING A SET
set1 = {'product','document','light','time','run'}
set2 = {'survival','shop','document','run'}
# Notice the use of {} instead of []
# FOR LOOP
for word in matching_words:
print(word)
# document
# run
如果您绝对需要一个列表,您可以将结果转换回(顺序仍然不可预测):
matching_words = list(matching_words)
nonmatching_words = list(nonmatching_words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.