是否有方便的方式从None
返回第一个元素或filter
?
filter(lambda x: x == 5, [3, 5, 5, 8]) # ?? 5
filter(lambda x: x == 35, [3, 5, 5, 8]) # ?? None
而不是必须拨打list()
然后再拨打[0]
?
我的问题是关于方法filter
而不是列表理解。
答案 0 :(得分:4)
filter
个对象本质上是迭代器。只需使用next
函数获取第一个值:
next(filter(lambda x: x == 35, [3, 5, 5, 8]), None)
如果next(it, None)
提升None
, next(it)
将返回StopIteration
。