Python 中列表中的第一個非空字串


給定一個字串列表,讓我們找出第一個非空元素。挑戰在於 - 在列表的開頭可能有一個、兩個或多個空字串,我們必須動態地找出第一個非空字串。

透過 next

如果當前元素為空值,我們將應用 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

透過過濾器

我們還可以使用 filter 條件實現這一點。filter 條件會捨棄空值,而我們會挑選第一個非空值。僅適用於 Python 2。

示例

 線上演示

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

更新於: 04-06-2020

599 次瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.