我的列表看起来像这样:
mylist = ([(0.1, 0.5),(0.4, 1.0)], [(0.2, 0.4),(0.15, 0.6)], None, [(0.35, 0.8),(0.05, 1.0)])
我想知道的是如何检查列表中的空条目或无,如果有,那么它应该继续忽略它。像,
if mylist == something :
do this
if mylist == [] or () or None :
ignore and continue
我无法将其放入代码中。谢谢。
答案 0 :(得分:4)
基本上,在python中
[], (), 0, "", None, False
所有这些意味着值为False
因此:
newList = [i for i in myList if i] # this will create a new list which does not have any empty item
emptyList = [i for i in myList if not i] # this will create a new list which has ONLY empty items
或者你问:
for i in myList:
if i:
# do whatever you want with your assigned values
else:
# do whatever you want with null values (i.e. [] or () or {} or None or False...)
然后你可以用你的新名单做任何你想做的事情:)
答案 1 :(得分:2)
for sublist in mylist:
if sublist is None:
#what to do with None
continue
elif not sublist and isinstance(sublist, list):
#what to do if it's an empty list
continue
elif not isinstance(sublist, list):
#what to do if it's not a list
continue
#what to do if it's a list and not empty
或者,您可以省略'continue'并将一般情况放在else
子句中,仅检查一些可能的情况,或嵌套ifs。
通常,如果您知道自己只获得None
或容器,则只需if not sublist: continue
就可以忽略空容器和None
。要从列表中筛选出这些值,请执行
mylist = [sublist for sublist in mylist if sublist]
编辑:您无法在update
功能中执行此操作。您应该预先过滤列表。你在哪里
mylist = oldlist[:]
替换为
mylist = [sublist for sublist in oldlist if sublist]
如果行名a
,b
或其他任何内容,但其余内容为空/ None
,请执行
mylist = [sublist for sublist in oldlist if sublist[1]]
这将过滤第一个项目/行标题的第二项目intead的真值。
答案 2 :(得分:1)
我会这样做:
for x in mylist:
if not x:
continue
#--> do what you want to do
但我不得不说理解列表的第一个答案更干净,除非你需要在for语句中做一些复杂的事情。
答案 3 :(得分:0)
这段代码怎么样:
for x in mylist:
if x is None or x == [] or x == ():
continue
else:
do this