python - 检查 python 列表中的下一个元素是否为空

标签 python list peek

所以我想要完成的是通过使用计数器 + 1 检查元素是否为空,但我不断得到索引超出范围,这实际上意味着下一个元素不存在,但我不想抛出异常,而是希望程序返回一个 bool 值到我的 if 语句是可能的..?本质上,我想实际查看字典中元组的下一个元素,看看它是否为空。

>>> counter = 1
>>> list = 1,2,3,4
>>> print list
>>> (1, 23, 34, 46)
>>> >>> list[counter]
23
>>> list[counter + 1]
34
>>> list[counter + 2]
46

>>> if list[counter + 3]:
...     print hello
... else:
...     print bye
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

最佳答案

如果你索引一个列表的不可用索引,你可以使用 try/catch 来捕获错误

最主要的是,用关键字命名变量是一种不好的做法,例如 list、set 等

try:
    if list[counter + 3]:
        print "yes"
except IndexError:
    print 'bye' 

关于python - 检查 python 列表中的下一个元素是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31115039/

相关文章:

python - 检查函数是否包含 pass

python - 为什么在Python中使用Button函数时,文本参数响应循环而命令参数不响应

python - 通过 pySerial 通过 Python 控制 Arduino

python - 如何在 python 中将值列表转换为字典?

python - 在列表中搜索字母

java - 用一副纸牌填充堆栈 Java

python - Canvas 上的 Kivy 插值

python-2.7 - 如何查看 Python 3 文件中的下一个字符?

python + libclang;来回迭代 : binding field comments to the field

python - 如何根据垂直位置重命名 python 列表列表中的重复元素?