列表理解错误
Mistake in list comprehension
Problem Solved!
我有两个随机生成的 python 整数列表。我想找到列表之间共有的数字。
使用列表理解,我想出了这个:
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
但是,这 returns 是一个空列表。我有一个使用完美运行的循环的工作程序:
for a in list_one:
for b in list_two:
if a == b and a not in new_list:
new_list.append(a)
我将其转换为列表理解时犯了什么错误?
我认为 2 个列表的交集不需要列表理解。
无论如何,您可以将代码修改为-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
print(new_list)
你也可以-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one if a in list_two and a not in new_list]
print(new_list)
你可以把它转换成set然后使用set1.intersection(set2).
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = list(set(list_one).intersection(set(list_two)))
print(new_list)
您不能在列表解析中引用同一个列表。
感谢 OP 评论中的@Keith 指出这一点。
这是一个简单的集合方法,
list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]
new_list = list(set(list_1) & set(list_2))
print(new_list)
与列表理解相比,它使用集合交集有很多好处:
- 输入列表不需要排序(尽管您可以使用
sorted()
函数对它们进行排序。
- 输入列表可以有不同的长度。
- 自动处理重复项的存在(集不接受这些)。
Problem Solved!
我有两个随机生成的 python 整数列表。我想找到列表之间共有的数字。
使用列表理解,我想出了这个:
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
但是,这 returns 是一个空列表。我有一个使用完美运行的循环的工作程序:
for a in list_one:
for b in list_two:
if a == b and a not in new_list:
new_list.append(a)
我将其转换为列表理解时犯了什么错误?
我认为 2 个列表的交集不需要列表理解。 无论如何,您可以将代码修改为-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
print(new_list)
你也可以-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one if a in list_two and a not in new_list]
print(new_list)
你可以把它转换成set然后使用set1.intersection(set2).
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = list(set(list_one).intersection(set(list_two)))
print(new_list)
您不能在列表解析中引用同一个列表。
感谢 OP 评论中的@Keith 指出这一点。
这是一个简单的集合方法,
list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]
new_list = list(set(list_1) & set(list_2))
print(new_list)
与列表理解相比,它使用集合交集有很多好处:
- 输入列表不需要排序(尽管您可以使用
sorted()
函数对它们进行排序。 - 输入列表可以有不同的长度。
- 自动处理重复项的存在(集不接受这些)。