失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python 检测列表中是否有空值 检查python列表中是否已经存在数字

python 检测列表中是否有空值 检查python列表中是否已经存在数字

时间:2020-12-09 14:09:07

相关推荐

python 检测列表中是否有空值 检查python列表中是否已经存在数字

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

解决方案

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 and a 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

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 检测列表中是否有空值 检查python列表中是否已经存在数字》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。