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

时间:2015-06-29 11:54:57

标签: python list peek

所以我想要完成的是通过使用计数器+ 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 个答案:

答案 0 :(得分:3)

如果索引列表中不可用的索引

,则可以使用try / catch来捕获错误

使用关键字命名变量,例如list,set等,这是一个不好的做法

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

答案 1 :(得分:2)

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

例如:

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

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

Python 3代码无一例外

    (kivy_venv) λ python main.py -d
[INFO   ] [Logger      ] Record log in C:\Users\DC\.kivy\logs\kivy_20-04-05_71.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.1.18
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.1.10
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.1.23
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "D:\Fazar\Terminal\kivy_venv\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "D:\Fazar\Terminal\kivy_venv\Scripts\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[DEBUG  ] [Cache       ] register <kv.lang> with limit=None, timeout=None
[DEBUG  ] [Cache       ] register <kv.image> with limit=None, timeout=60
[DEBUG  ] [Cache       ] register <kv.atlas> with limit=None, timeout=None
[INFO   ] [ImageLoaderFFPy] Using ffpyplayer 4.3.1
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_ffpyplayer, img_gif
[DEBUG  ] [Cache       ] register <kv.texture> with limit=1000, timeout=60
[DEBUG  ] [Cache       ] register <kv.shader> with limit=1000, timeout=3600
[DEBUG  ] [App         ] Loading kv <.\pong.kv>
[INFO   ] [Window      ] Provider: sdl2
[CRITICAL] [Window      ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
sdl2 - ValueError: Not a boolean: 400
  File "D:\Fazar\Terminal\kivy_venv\lib\site-packages\kivy\core\__init__.py", line 71, in core_select_lib
    cls = cls()
  File "D:\Fazar\Terminal\kivy_venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 152, in __init__
    super(WindowSDL, self).__init__()
  File "D:\Fazar\Terminal\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 981, in __init__
    self.create_window()
  File "D:\Fazar\Terminal\kivy_venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 284, in create_window
    resizable = Config.getboolean('graphics', 'resizable')
  File "D:\Fazar\Software\Python37\lib\configparser.py", line 828, in getboolean
    raw=raw, vars=vars, fallback=fallback, **kwargs)
  File "D:\Fazar\Software\Python37\lib\configparser.py", line 808, in _get_conv
    **kwargs)
  File "D:\Fazar\Software\Python37\lib\configparser.py", line 802, in _get
    return conv(self.get(section, option, **kwargs))
  File "D:\Fazar\Software\Python37\lib\configparser.py", line 1160, in _convert_to_boolean
    raise ValueError('Not a boolean: %s' % value)

[CRITICAL] [App         ] Unable to get a Window, abort.

打印此内容:

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}")