python - 如何在python中找到多个不重复的数字?
问题描述
我有一个在列表中查找非重复元素的方法:
def dupes(a):
s = {}
for ele in a:
if ele not in s:
s[ele] = 1
else:
s[ele] += 1
for x in s:
if s[x] == 1:
return 'this is the only non-repeating element value is :', s[x], 'and the key is :', x
return
l = [4, 7, 4, 5, 7, 6, 5, 6, 10]
cd = dupes(l)
print("This is dupes: ", cd)
代码运行成功,输出如下:
This is dupes: ('this is the only non-repeating element value is :', 1, 'and the key is :', 10)
但是当我尝试在列表中添加多个非重复元素时,输出不会改变。例如,如果我在列表末尾添加 11,则输出仍然与上面相同。
任何想法?
解决方案
实际上,当您在第 10 行返回时,函数就结束了。这是为了以防您还不了解列表理解,因为许多人已经使用该技术为您提供了解决方案。我只会给你一个简单的解决方案,它将返回一个非重复数字的列表。
def dupes(a):
s = {}
non_dupes = []
for ele in a:
if ele not in s:
s[ele] = 1
else:
s[ele] += 1
for x in s:
if s[x] == 1:
non_dupes.append(x)
return non_dupes
l = [4, 7, 4, 5, 7, 6, 5, 6, 10, 11]
cd = dupes(l)
print("This is dupes: ", cd)
推荐阅读
- python - 如何在用户函数中返回两个数据框
- ios - didSelectRowAt 将数据传递到新视图
- php - 无法将数据插入mysql数据库
- java - 显示在另一个类/文件中创建的菜单栏
- javascript - 自定义 Wordpress 插件:无法读取 null 的属性“parentElement”
- bash - awk 将三列中的数字相加,只返回一列
- opengl - 使用 GL_SHADER_STORAGE_BUFFER 将数组传递给片段着色器
- java - Velocity 1.7 - 有时 Directive.postRender 在 Velocity.evaluate 中抛出 NullPointerException
- angular - 如何获取在角度 7 中选中的多个复选框的计数
- javascript - 为getelementbyid动态生成的HTML获取null