【问题标题】:List of the first item in a sublist子列表中第一项的列表
【发布时间】:2022-11-28 04:27:53
【问题描述】:

我想要一个显示我输入的子列表的第一个元素的列表。

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

哪个有效,但是当我尝试做

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

由于 [] 出现错误,我该如何解决?

【问题讨论】:

    标签: python


    【解决方案1】:

    在您的列表理解中添加一个条件,以便跳过空列表。

    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]
    

    【讨论】:

    • 可以只是if item
    • 真的。在这种情况下,我选择更明确。
    【解决方案2】:

    添加条件以检查项目是否有数据。

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

    你也可以这样做:

    def firstelements(w):
        return list(zip(*filter(None, w)))[0]
    

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2014-09-22
      相关资源
      最近更新 更多