Skip to main content
 首页 » 编程设计

Python:如何避免 'list assignment index out of range'

2025年05月04日14jpfss

尝试搜索但找不到任何内容。我正在寻找最简单的替换

if myList and len(myList)>4 

用更短的东西:

myList = [1,2,3,4,5] 
 
if myList and len(myList)>4:  
    print myList[4], len(myList) 

自从

if not myList[4] 

不工作。

请您参考如下方法:

不太确定问的是什么,但我敢猜测 EAFP这是正确的概念。

try: 
    myList[4] 
except IndexError: 
    # handle it 

基本上,尝试用索引 4 做你想做的事。如果你做不到,那是因为 IndexError,按照你处理它的方式处理它,如果你的 if len(myList) > 4 失败。