且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查python列表中是否已经存在一个数字

更新时间:2022-05-19 06:16:21

你可以做到

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