在列表和列表中查找匹配的单词和不匹配的单词

2024-10-03 09:12:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python初学者,我有两个列表

list1 = ['product','document','light','time','run']
list2 = ['survival','shop','document','run']

我想找到匹配的词和不匹配的词

这里是示例结果

matching_words = ['document','run']
notmatching_words = ['product','light','time','survival','shop']

我该怎么办


Tags: run示例列表timeproductshopdocumentlight
2条回答

回答的解决方案工作得非常好,但我想提出另一个使用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)

尝试:

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))

相关问题 更多 >