如何检查 Python 列表中是否存在第 n 个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15554255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:23:02  来源:igfitidea点击:

How to check if the n-th element exists in a Python list?

pythonlist

提问by A B

I have a list in python

我在 python 中有一个列表

x = ['a','b','c']

with 3 elements. I want to check if a 4th element exists without receiving an error message.

有 3 个元素。我想在没有收到错误消息的情况下检查第四个元素是否存在。

How would I do that?

我该怎么做?

回答by Martijn Pieters

You check for the length:

您检查长度:

len(x) >= 4

or you catch the IndexErrorexception:

或者您捕获IndexError异常:

try:
    value = x[3]
except IndexError:
    value = None  # no 4th index

What you use depends on how often you can expectthere to be a 4th value. If it is usually there, use the exception handler (better to ask forgiveness); if you mostly do nothave a 4th value, test for the length (look before you leap).

您使用什么取决于您期望出现第四个值的频率。如果它通常在那里,请使用异常处理程序(最好请求原谅);如果您大多没有第 4 个值,请测试长度(在跳跃之前查看)。

回答by Silas Ray

You want to check if the list is 4 or more elements long?

您想检查列表是否有 4 个或更多元素?

len(x) >= 4

You want to check if what would be the fourth element in a series is in a list?

您想检查一个系列中的第四个元素是否在列表中?

'd' in x