1

所以我想要完成的是通过使用 counter + 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
4

4 回答 4

4

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

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

try:
    if list[counter + 3]:
        print "yes"
except IndexError:
    print 'bye' 
于 2015-06-29T11:58:14.583 回答
2

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

例如:

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

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

于 2015-06-29T11:57:18.497 回答
1

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

if index + 1 > len(my_list):
    print "Index is to big"
else:
    print "Index is present"
于 2015-06-29T11:59:55.393 回答
1

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
于 2020-04-05T08:09:34.787 回答