首页 > 解决方案 > 用一行代码从两个单独的列表生成一个新列表

问题描述

我正在尝试一项要求您执行以下操作的练习:

编写一个程序,该程序返回一个列表,该列表仅包含列表之间共有的元素(没有重复项)。确保您的程序适用于两个不同大小的列表。

我能够做到这一点,但额外的挑战之一是:

用一行 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]

我的单行列表理解似乎失败了,有人能指出这是为什么吗?

标签: pythonlistlist-comprehension

解决方案


一种基本方法是将 newList 转换为 set ,然后将其重新转换为 list

print(list(set(newList)))

或者通过使用没有任何循环的集合交集

print(list(set(list_1).intersection(list_2)))

推荐阅读