[英]Accessing nth element of list of lists python - index does not exist error
I have data of the following form:我有以下形式的数据:
list_of_numbers = [[8, 10], [10, 8, 1, 0], [6], [4, 0, 1, 2, 3], [12]]
I am trying to extract the first and second element of this list as follows:我正在尝试提取此列表的第一个和第二个元素,如下所示:
[n[0] for n in list_of_numbers]
This works well for the first element, however, when I try to extract the second element in the same way I get an error (IndexError: list index out of range).这对第一个元素很有效,但是,当我尝试以同样的方式提取第二个元素时,我得到一个错误(IndexError:列表索引超出范围)。 I realise this is because the some of the lists in the list do not have a second element.我意识到这是因为列表中的某些列表没有第二个元素。 However, I need to extract the second element whenever it exists, and have NaN/missing when it doesn't.但是,我需要在第二个元素存在时提取它,并且在它不存在时有 NaN/missing。 How do I go about implementing this in my code?我如何在我的代码中实现这一点?
Thanks!谢谢!
You could use a conditional list comprehension to check the length of the inner lists and index them only if they are above a certain length:您可以使用条件列表推导来检查内部列表的长度并仅在它们超过一定长度时对其进行索引:
index = 1
[i[index] if len(i)>index else float('nan') for i in list_of_numbers]
# [10, 8, nan, 0, nan]
This solution puts None
when the list is not long enough.当列表不够长时,此解决方案将None
放置。 You can replace it with whatever you like (eg np.nan
).你可以用你喜欢的任何东西替换它(例如np.nan
)。
Solution:解决方案:
i = 1
[None if len(n) <= i else n[i] for n in list_of_numbers]
Result:结果:
[10, 8, None, 0, None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.