且构网

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

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

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

您可以做到

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