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