Python 中列表中的第一个非空字符串
pythonserver side programmingprogramming更新于 2026/1/22 22:04:17
给定一个字符串列表,让我们找出第一个非空元素。挑战在于 - 列表开头可能有一个、两个或多个空字符串,我们必须动态地找出第一个非空字符串。
使用 next
如果当前元素为空,我们应用 next 函数继续移动到下一个元素。
示例
listA = ['','top', 'pot', 'hot', ' ', 'shot']
# 给定列表
print(" 给定列表:\n " ,listA)
# 使用 next()
res = next(sub for sub in listA if sub)
# 打印结果
print("The first non empty string is : \n",res)
输出
运行上述代码得到以下结果 −
给定列表: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
使用 filer
我们也可以使用过滤条件来实现这一点。过滤条件将丢弃空值,我们将选择第一个非空值。仅适用于 python2。
示例
listA = ['','top', 'pot', 'hot', ' ','shot']
# 给定列表
print(" 给定列表:\n " ,listA)
# 使用 filter()
res = filter(None, listA)[0]
# 打印结果
print("The first non empty string is : \n",res)
输出
运行上述代码得到以下结果 −
给定列表: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

