dealing with an empty list inside a list
我有一个列表,看起来像这样:
1 | 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)]) |
我想知道的是如何检查列表中的空条目或无条目,如果有空条目,它应该继续忽略它。有点像
1 2 3 4 5 | if mylist == something : do this if mylist == [] or () or None : ignore and continue |
我无法将其输入代码。谢谢您。
基本上,在python中
1 | [], (), 0,"", None, False |
所有这些都意味着值是假的
因此:
1 2 3 | 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 |
或者按照你的要求:
1 2 3 4 5 | 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 3 4 5 6 7 8 9 10 11 | 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 |
或者,您可以省略"continues",将一般情况放在
一般来说,如果你知道你只会得到一个
1 | mylist = [sublist for sublist in mylist if sublist] |
编辑:在
1 | mylist = oldlist[:] |
用它代替
1 | mylist = [sublist for sublist in oldlist if sublist] |
如果行名为
1 | mylist = [sublist for sublist in oldlist if sublist[1]] |
这将过滤第一个项目/行标题的第二个项目集成的真值。
我就这么做:
1 2 3 4 5 | for x in mylist: if not x: continue #--> do what you want to do |
但我不得不说,第一个带理解列表的答案更清晰,除非你需要在for语句中做一些复杂的事情。
这段代码怎么样:
1 2 3 4 5 | for x in mylist: if x is None or x == [] or x == (): continue else: do this |