Common elements between two lists with no duplicates(两个列表之间没有重复的公共元素)
问题描述
问题是这样的,取两个列表,比如说这两个:
Problem is this, take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
并编写一个程序,该程序返回一个列表,该列表仅包含列表之间共有的元素(没有重复).确保您的程序适用于两个不同大小的列表.
And 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.
这是我的代码:
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for i in a:
if i in b and i not in c:
c.append([i])
print(c)
尽管有i not in c"语句,但我的输出仍然给我重复.为什么是这样?我敢肯定它很明显,我只是看不到它!
My output is still giving me duplicates despite the 'i not in c' statement. why is this? I'm sure its blatantly obvious, I just cant see it!
推荐答案
- 您将包含
i
的列表附加到c
,因此i not in c
将始终返回 <代码>正确代码>.您应该单独附加i
:c.append(i)
- You are appending a list containing
i
toc
, soi not in c
will always returnTrue
. You should appendi
on its own:c.append(i)
或者
只需使用集合(如果顺序不重要):
Simply use sets (if order is not important):
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = set(a) & set(b) # & calculates the intersection.
print(c)
# {1, 2, 3, 5, 8, 13}
编辑作为@Ev.Kounis 在评论中建议,您将通过使用获得一些速度c = set(a).intersection(b)
.
EDIT As @Ev. Kounis suggested in the comment, you will gain some speed by using
c = set(a).intersection(b)
.
这篇关于两个列表之间没有重复的公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:两个列表之间没有重复的公共元素


- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何将一个类的函数分成多个文件? 2022-01-01
- 沿轴计算直方图 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01