Skip to main content
 首页 » 编程设计

python之处理列表中的空列表

2025年05月04日17yjmyzz

我有一个看起来像这样的列表:

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       

我无法将其放入代码中。谢谢。

请您参考如下方法:

基本上,在 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...) 

然后你可以用你的新列表做任何你想做的事情:)