简体   繁体   English

子列表中第一项的列表

[英]List of the first item in a sublist

I want a list that displays the first element of the sublists I input.我想要一个显示我输入的子列表的第一个元素的列表。

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

Which works, but when I try doing哪个有效,但是当我尝试做

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

there's an error because of the [] .由于[]出现错误。 How can I fix this?我怎样才能解决这个问题?

Add a condition to your list comprehension so that empty lists are skipped.在您的列表理解中添加一个条件,以便跳过空列表。

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

If you wish to represent that empty list with something but don't want an error you might use a conditional expression in your list comprehension.如果您希望用某些东西表示该空列表但又不想出错,您可以在列表理解中使用条件表达式。

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

Add a condition to check if the item has data.添加条件以检查项目是否有数据。

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

Below are 3 more ways you can write it that don't require a condition.以下是另外 3 种不需要条件的编写方式。 filter strips out None /"Empty" values. 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