check if a number already exist in a list in python(检查python列表中是否已经存在一个数字)
问题描述
我正在编写一个 python 程序,我将在其中将数字附加到一个列表中,但我不希望列表中的数字重复.那么在执行 list.append()
之前如何检查一个数字是否已经在列表中?
I am writing a python program where I will be appending numbers into a list, but I don't want the numbers in the list to repeat. So how do I check if a number is already in the list before I do list.append()
?
推荐答案
你可以做到
if item not in mylist:
mylist.append(item)
但是你真的应该使用一个集合,像这样:
But you should really use a set, like this :
myset = set()
myset.add(item)
如果顺序很重要但您的列表非常大,您可能应该同时使用列表和集合,如下所示:
If order is important but your list is very big, you should probably use both a list and a set, like so:
mylist = []
myset = set()
for item in ...:
if item not in myset:
mylist.append(item)
myset.add(item)
这样,您可以快速查找元素是否存在,但仍保持排序.如果您使用简单的解决方案,您将获得 O(n) 的查找性能,如果您的列表很大,这可能会很糟糕
This way, you get fast lookup for element existence, but you keep your ordering. If you use the naive solution, you will get O(n) performance for the lookup, and that can be bad if your list is big
或者,正如@larsman 指出的那样,您可以使用 OrderedDict 达到同样的效果:
Or, as @larsman pointed out, you can use OrderedDict to the same effect:
from collections import OrderedDict
mydict = OrderedDict()
for item in ...:
mydict[item] = True
这篇关于检查python列表中是否已经存在一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查python列表中是否已经存在一个数字


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01