gpt4 book ai didi

python - Python 的 list.index() 函数,当没有找到时不会抛出异常

转载 作者:IT老高 更新时间:2023-10-28 20:21:06 28 4
gpt4 key购买 nike

如果项目不存在,Python 的 list.index(x) 会引发异常。有没有更好的不需要处理异常的方法?

最佳答案

如果你不关心匹配元素在哪里,那么使用:

found = x in somelist

如果您在乎,请使用 LBYL带有 conditional expression 的样式:

i = somelist.index(x) if x in somelist else None

关于python - Python 的 list.index() 函数,当没有找到时不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8197323/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com