Python列表中的第一个非空字符串
给定一个字符串列表,让我们找出第一个非空元素。挑战在于–列表开头可能有一个,两个或多个空字符串,我们必须动态地找出第一个非空字符串。
下一个
如果当前元素为null,则应用next函数继续移动到下一个元素。
示例
listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using next()res = next(sub for sub in listA if sub)
# printing result
print("The first non empty string is : \n",res)输出结果
运行上面的代码给我们以下结果-
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
与文件管理器
我们也可以使用过滤条件来实现。过滤条件将丢弃空值,我们将选择第一个非空值。仅适用于python2。
示例
listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using filter()res = filter(None, listA)[0]
# printing result
print("The first non empty string is : \n",res)输出结果
运行上面的代码给我们以下结果-
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
热门推荐
10 中午生日家庭祝福语简短
11 给干爸过年祝福语简短
12 上岸离职祝福语大全简短
13 朋友入伙搬家祝福语简短
14 硕士毕业蛋糕祝福语简短
15 亲属登门拜年祝福语简短
16 同事有趣祝福语大全简短
17 虎年台词祝福语大全简短
18 春天变冷祝福语简短