python - 比较两个重复的字符串列表并打印差异
问题描述
我对 Python 很陌生,我的代码有问题。我想编写一个与列表进行比较并打印给用户的函数,哪些元素存在于 list1 中但不存在于 lis2 中。
例如输入可以是:
list1=["john", "jim", "michael", "bob"]
list2=["james", "edward", "john", "jim"]
然后输出应该是:
Names in list1, but not in list2: Michael, Bob
Names in list2, but not in list1: James, Edward
谢谢你的帮助!
(编辑:这是我到目前为止的代码:
def compare_lists(list1, list2):
for name1 in list1:
if name1 not in list2:
print("Names in list1, but not in list2: ", name1)
for name2 in list2:
if name2 not in list1:
print("Names in list1, but not in list2: ", name2)
我的问题是输出打印了两次:
Names in list1, but not in list2: Michael
Names in list1, but not in list2: Bob
Names in list2 but not in list1: James
Names in list2 but not in list1: Edward
解决方案
尝试这个:
list1=["john", "jim", "michael", "bob"]
list2=["james", "edward", "john", "jim"]
names1 = [name1 for name1 in list1 if name1 not in list2]
names2 = [name2 for name2 in list2 if name2 not in list1]
print(names1)
print(names2)
推荐阅读
- android - 如何在 Android 上禁用热键/快捷方式?
- flutter - 如何在 MyApp 的 build 方法中调用 Stateless 小部件,其状态由其 Stateful Parent 管理
- python - 我正在尝试为mimic2 预处理数据集,但我被正式卡住了。新手提醒
- c# - 在 GetAuthenticationStateAsync 之外设置声明不会影响
标签 - database - 在微服务中初始化和迁移 Postgresql 模式的最佳方法
- python - Python列表与数组,如果我们知道第一个元素的位置,如何计算内存中的位置
- android - Android Studio:java 和 javax 导入的未解决参考,但项目编译
- sql - 在 Bigquery 中使用 JOIN 进行计数
- google-chrome - 无法在 Google Chrome Linux 中更改权限
- docker - 如何在 Docker 中运行 Hadoop DFSIO MapReduce 基准测试?