Python 如何获取列表中的第一个非空项
我将如何获取以下信息:Python 如何获取列表中的第一个非空项,python,Python,我将如何获取以下信息: l=[None, None, 'hello', 'hello'] first(l) ==> 'hello' l = [None, None, None, None] first(l) ==> None first = next((el for el in your_list if el is not None), None) 我可以尝试使用列表理解来执行此操作,但如果没有项目,则会出现错误。使用以下方法: l=[None, None, 'hello',
l=[None, None, 'hello', 'hello']
first(l) ==> 'hello'
l = [None, None, None, None]
first(l) ==> None
first = next((el for el in your_list if el is not None), None)
我可以尝试使用列表理解来执行此操作,但如果没有项目,则会出现错误。使用以下方法:
l=[None, None, 'hello', 'hello']
first(l) ==> 'hello'
l = [None, None, None, None]
first(l) ==> None
first = next((el for el in your_list if el is not None), None)
这将在您的_列表
上构建一个gen exp,然后尝试检索第一个未找到值的值(该值为空列表/所有值均为无),它将返回默认值无
(或根据需要更改)
如果要将其设置为函数,则:
def first(iterable, func=lambda L: L is not None, **kwargs):
it = (el for el in iterable if func(el))
if 'default' in kwargs:
return next(it, kwargs[default])
return next(it) # no default so raise `StopIteration`
然后用作:
fval = first([None, None, 'a']) # or
fval = first([3, 4, 1, 6, 7], lambda L: L > 7, default=0)
等等。如果我正确理解了问题
l = [None, None, "a", "b"]
for item in l:
if item != None:
first = item
break
print first
输出:
a
您可以使用while循环进行迭代。类似于:而不是None idx+=1.b
第一个是什么我错了。它输出第一个。哈首先是一个函数,对吗?好吧,它可以被做成一个函数,然后(过滤器(无,[None,None,'a','b','c'))