python - 在列表和列表中查找匹配的单词和不匹配的单词
问题描述
我是学习 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))
推荐阅读
- android - 如何在其他活动中发送价值?
- android - 打开任何类型的文件作为图像
- python - Python 代码在线运行但不在 Jupyter Notebook 中?
- c# - 禁用从 WPF 安装程序的外部源复制和粘贴内容
- c# - C# 中的千位分隔符用于更多的小数点
- python - 获取 3D 向量并生成角度分布图
- android - TextInputLayout 删除不需要的空间
- git - 合并提交后在 git ci/cd 上触发脚本
- wpf - 升级到 Windows 10 后,拖放在 WPF 应用程序中不起作用
- string - 检索存储在 SQFlite 数据库 (Flutter) 中的数据?