【问题标题】:Accessing nth element of list of lists python - index does not exist error访问列表python列表的第n个元素-索引不存在错误
【发布时间】:2019-10-01 16:36:58
【问题描述】:

我有以下形式的数据:

list_of_numbers = [[8, 10], [10, 8, 1, 0], [6], [4, 0, 1, 2, 3], [12]]

我正在尝试提取此列表的第一个和第二个元素,如下所示:

[n[0] for n in list_of_numbers]

这适用于第一个元素,但是,当我尝试以相同的方式提取第二个元素时,我得到一个错误(IndexError:列表索引超出范围)。我意识到这是因为列表中的某些列表没有第二个元素。但是,我需要在第二个元素存在时提取它,并在它不存在时提取 NaN/缺失。我该如何在我的代码中实现这一点?

谢谢!

【问题讨论】:

标签: python list


【解决方案1】:

您可以使用条件列表推导来检查内部列表的长度并仅在它们超过一定长度时对其进行索引:

index = 1
[i[index] if len(i)>index else float('nan') for i in list_of_numbers]
# [10, 8, nan, 0, nan]

【讨论】:

    【解决方案2】:

    当列表不够长时,此解决方案会放置None。您可以将其替换为您喜欢的任何内容(例如np.nan)。

    解决方案:

    i = 1
    [None if len(n) <= i else n[i] for n in list_of_numbers]
    

    结果:

    [10, 8, None, 0, None]
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多