繁体   English   中英

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

[英]Checking if the next element in a python list is empty

所以我想要完成的是通过使用计数器 + 1 检查元素是否为空,但我一直让索引超出范围,这实际上意味着下一个元素不存在,但我希望程序返回而不是抛出异常我的 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 来捕获错误

最重要的是,使用关键字(即列表、设置等)命名变量是一种不好的做法

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

您可以使用len检查您是否在范围内。

例如:

>>> l = 1,2,3,4
>>> len(l)
4

此外,元组不是列表。 将事物命名为listarray等通常被认为是不好的做法。

检查元组或列表中是否存在索引的最简单方法是将给定的索引与其长度进行比较。

if index + 1 > len(my_list):
    print "Index is to big"
else:
    print "Index is present"

Python 3 代码无一例外:

my_list = [1, 2, 3]
print(f"Lenght of list: {len(my_list)}")
for index, item in enumerate(my_list):
    print(f"We are on element: {index}")
    next_index = index + 1
    if next_index > len(my_list) - 1:
        print(f"Next index ({next_index}) doesn't exists")
    else:
        print(f"Next index exists: {next_index}")

打印这个:

>>> Lenght of list: 3
>>> We are on element: 0
>>> Next index exists: 1
>>> We are on element: 1
>>> Next index exists: 2
>>> We are on element: 2
>>> Next index (3) doesn't exists

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM