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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14667578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:06:54  来源:igfitidea点击:

check if a number already exist in a list in python

pythonlist

提问by PhoonOne

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()?

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

采纳答案by raph.amiard

You could do

你可以做

if item not in mylist:
     mylist.append(item)

But you should really use a set, like this :

但是你真的应该使用一个集合,像这样:

myset = set()
myset.add(item)

EDIT:If order is important but your list is very big, you should probably use both a list anda set, like so:

编辑:如果顺序很重要但您的列表非常大,您可能应该同时使用列表集合,如下所示:

mylist = []
myset = set()
for item in ...:
    if item not in myset:
        mylist.append(item)
        myset.add(item)

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

这样,您可以快速查找元素是否存在,但您可以保持排序。如果您使用天真的解决方案,您将获得 O(n) 的查找性能,如果您的列表很大,那可能会很糟糕

Or, as @larsman pointed out, you can use OrderedDict to the same effect:

或者,正如@larsman 指出的那样,您可以使用 OrderedDict 达到相同的效果:

from collections import OrderedDict

mydict = OrderedDict()
for item in ...:
    mydict[item] = True

回答by Rohit Jain

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -

如果您想在列表中包含唯一元素,那么为什么不使用集合,当然,如果顺序对您来说无关紧要:-

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: -

如果订单是一个问题,那么您可以使用:-

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSetrecipe, which is referred to in Python Documentation

您还可以找到一个OrderedSet配方,它在Python 文档中被引用

回答by Keith

You could probably use a set object instead. Just addnumbers to the set. They inherently do not replicate.

您可能可以改用 set 对象。只是add数字到集合。它们本质上不会复制。

回答by Octipi

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

如果您希望您的数字按升序排列,您可以将它们添加到一个集合中,然后将集合排序到一个升序列表中。

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order