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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿