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

编程入门 行业动态 更新时间:2024-10-12 16:29:06
本文介绍了检查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列表中是否已经存在一个数字

本文发布于:2023-11-28 18:28:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   列表中   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!