python - 用一行代码从两个单独的列表生成一个新列表
问题描述
我正在尝试一项要求您执行以下操作的练习:
编写一个程序,该程序返回一个列表,该列表仅包含列表之间共有的元素(没有重复项)。确保您的程序适用于两个不同大小的列表。
我能够做到这一点,但额外的挑战之一是:
用一行 Python 写这个
我想出了以下代码:
list_1 = [1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 89]
list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 3, 13]
newList = []
newList = [x for x in list_1 if x in list_2 if x not in newList] #attempting one line
print(newList)
newList = []
for x in list_1:
if x in list_2 and x not in newList:
newList.append(x)
print(newList)
我得到以下结果:
[1, 1, 2, 3, 3, 3, 3, 3, 3, 3]
[1, 2, 3]
我的单行列表理解似乎失败了,有人能指出这是为什么吗?
解决方案
一种基本方法是将 newList 转换为 set ,然后将其重新转换为 list
print(list(set(newList)))
或者通过使用没有任何循环的集合交集
print(list(set(list_1).intersection(list_2)))
推荐阅读
- arrays - 我想在 mongodb 中更新集合中的文档
- windows - ping -w timeout 的最小值在实践中
- python - 为什么这个 itertools 函数在另一个函数之外工作而不在内部工作?
- spring-boot - Gradle 到 6.6.1 得到 无法接收来自守护进程的消息
- elasticsearch - 如何在elasticsearch中更新和剥离数组字段的第一个字符
- python - 使用 CSV 的 Python 散点图
- codeigniter - IIS 下的 Codeigniter - SOAP“方法不允许”
- microsoft-graph-api - 在 MS Graph API 中是否有一个 webhook 可以知道一个人在团队通话中与谁交谈?
- java - 带有 ViewPager2 的 FragmentStateAdapter 显示不正确的片段
- java - 按列查找已排序二维数组中二维数组元素的索引