检查python列表中是否已经存在数字 [英] check if a number already exist in a list in python

查看:1421
本文介绍了检查python列表中是否已经存在数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python代码,将数字添加到列表中,但是我不希望列表中的数字重复.那么,在执行list.append()之前,如何检查列表中是否已存在数字?

I am writing a python code where I will be appending numbers into a list, but I dont 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列表中是否已经存在数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆