在Python中迭代非None项

时间:2021-07-07 19:26:34

I have a list of strings, some which happen to be None:

我有一个字符串列表,其中一些恰好是None:

headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]

Now I would like to iterate over this list, but skip the None entries. For instance, something like this would be nice:

现在我想迭代这个列表,但跳过None条目。例如,像这样的东西会很好:

for header in headers if header: print(header)

But this doesn't work. There are two ways I could get this to work, but I don't like either method:

但这不起作用。有两种方法可以让它工作,但我不喜欢这两种方法:

for header in (item for item in headers if item): print(header)

and

for header in headers:
    if header: print(header)

I just was curious if there was a better way. I feel like ignoring None's should be quite fundamental.

我只是好奇是否有更好的方法。我觉得无视无应该是非常基本的。

4 个解决方案

#1


11  

headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
for header in filter(None, headers):
    print header

#2


5  

You can use filter:

你可以使用过滤器:

headers = filter(None, headers)

#3


1  

You can filter out the Nones with a simple list comprehension:

您可以使用简单的列表推导过滤掉Nones:

headers = [header for header in headers if header]

Then call your code:

然后调用你的代码:

for header in headers:
    print(header)

#4


1  

You can get rid of the None items with a list comprehension:

你可以通过列表理解去掉None项:

headers = [item for item in headers if item is not None]
for item in header:
    print item

#1


11  

headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
for header in filter(None, headers):
    print header

#2


5  

You can use filter:

你可以使用过滤器:

headers = filter(None, headers)

#3


1  

You can filter out the Nones with a simple list comprehension:

您可以使用简单的列表推导过滤掉Nones:

headers = [header for header in headers if header]

Then call your code:

然后调用你的代码:

for header in headers:
    print(header)

#4


1  

You can get rid of the None items with a list comprehension:

你可以通过列表理解去掉None项:

headers = [item for item in headers if item is not None]
for item in header:
    print item