如何检查Python列表中是否存在第n个元素? [英] How to check if the n-th element exists in a Python list?

查看:92
本文介绍了如何检查Python列表中是否存在第n个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个列表

I have a list in python

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

具有3个元素.我想检查第四个元素是否存在而没有收到错误消息.

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

我该怎么做?

推荐答案

您检查长度:

len(x) >= 4

,或者您捕获到IndexError异常:

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

您使用什么取决于您可以多久<一次>期望有一个第四值.如果通常在那儿,请使用异常处理程序(更好地请求宽恕);如果您大多数情况下没有具有第4个值,请测试长度(跳跃前先看).

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

这篇关于如何检查Python列表中是否存在第n个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆