簡體   English   中英

子列表中第一項的列表

[英]List of the first item in a sublist

我想要一個顯示我輸入的子列表的第一個元素的列表。

def firstelements(w):
    return [item[0] for item in w]

哪個有效,但是當我嘗試做

firstelements([[10,10],[3,5],[]])

由於[]出現錯誤。 我怎樣才能解決這個問題?

在您的列表理解中添加一個條件,以便跳過空列表。

def firstelements(w):
    return [item[0] for item in w if item != []]

如果您希望用某些東西表示該空列表但又不想出錯,您可以在列表理解中使用條件表達式。

def firstelements(w):
    return [item[0] if item != [] else None for item in w]
>>> firstelements([[10,10],[3,5],[]])
[10, 3, None]

添加條件以檢查項目是否有數據。

def firstelements(w):
    return [item[0] for item in w if item]

以下是另外 3 種不需要條件的編寫方式。 filter None /"Empty" 值。

def firstelements(w):
    return list(zip(*filter(None, w)))[0]
def firstelements(w):
    return [item[0] for item in filter(None, w)]
def firstelements(w):
    return [i for (i,*_) in filter(None, w)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM