使用一行代码从两个单独的列表生成一个新列表
Generating a new List from two Separate Lists with one Line of Code
我正在尝试一项要求您执行的练习:
write a program that returns a list that contains only the elements
that are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes.
我能够做到这一点,但额外的挑战之一是:
Write this in one line of 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)))
我正在尝试一项要求您执行的练习:
write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
我能够做到这一点,但额外的挑战之一是:
Write this in one line of 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)))