简体   繁体   English

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

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

So what I am trying to accomplish is to check whether an element is empty by using a counter + 1 but I keep getting index out of range which essentially means the next element doesnt exist, but instead of throwing an exception I want the program to return a boolean to my if statement is that possible..?所以我想要完成的是通过使用计数器 + 1 检查元素是否为空,但我一直让索引超出范围,这实际上意味着下一个元素不存在,但我希望程序返回而不是抛出异常我的 if 语句的布尔值是否可能..? In essence I want to peek forward to the next element of a tuple within a dictionary actually and see if it is empty.从本质上讲,我想实际查看字典中元组的下一个元素,看看它是否为空。

>>> 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

You could use try/catch to catch error if you index a not available index of a list如果索引列表的不可用索引,则可以使用 try/catch 来捕获错误

And the main thing it is a bad practice to name variable with keywords ie list,set etc最重要的是,使用关键字(即列表、设置等)命名变量是一种不好的做法

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

You can use len to check for whether you are within the range.您可以使用len检查您是否在范围内。

For example:例如:

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

Also, a tuple is not a list.此外,元组不是列表。 It is generally considered bad practice to name things as list or array etc.将事物命名为listarray等通常被认为是不好的做法。

The easiest way to check presence of index in tuple or list is to compare given index to length of it.检查元组或列表中是否存在索引的最简单方法是将给定的索引与其长度进行比较。

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

Python 3 code without exceptions: 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}")

Prints this:打印这个:

>>> 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