python代码中的错误(IndexError:列表赋值索引超出范围)初学者级别

问题描述 投票:-1回答:4

在运行以下代码时

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

# write your for loop here
for index in range(len(names)):
    usernames[index] = names[index].lower().replace(" ", "_")


print(usernames)

观察到此错误

Traceback (most recent call last):
  File "vm_main3.py", line 47, in <module>
    import main
  File "/tmp/vmuser_kncqjadnfl/main.py", line 2, in <module>
    import studentMain
  File "/tmp/vmuser_kncqjadnfl/studentMain.py", line 1, in <module>
    import usernames
  File "/tmp/vmuser_kncqjadnfl/usernames.py", line 6, in <module>
    usernames[index] = names[index].lower().replace(" ", "_")
IndexError: list assignment index out of range

任何帮助将不胜感激。

python
4个回答
2
投票

大多数错误都不言自明。

你的列表usernames被初始化为空,即长度为0.所以无论index是什么整数,usernames[index]都会尝试访问一个不存在的元素。这就是为什么你得到一个IndexError

你想要做的是将元素追加到列表usernamesappend方法做到了。所以你的for循环应该是:

for index in range(len(names)):
    usernames.append(names[index].lower().replace(" ", "_"))

尝试阅读任何python-beginner关于列表的教程,或至少在继续之前阅读the official documentation


0
投票

试图设置usernames[index]是无效的,因为它是一个空列表,但你正在写一个值给usernames[0]。您可以尝试以下格式:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

# write your for loop here
for index in range(len(names)):
    print(index)
    usernames.append(names[index].lower().replace(" ", "_"))


print(usernames)

0
投票

有很多方法可以使用下划线(_)获取List所有名称

  1. 获得具有相同案例的所有名称
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

for index in names:
    usernames.append(index.replace(" ", "_"))

print(usernames)
  1. 如果你想要小写字母只需要替换这一行

usernames.append(index.lower().replace(" ", "_"))


0
投票

试试这个优化的代码:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = [val.lower().replace(" ", "_") for val in names ]
print(usernames)

输出:

['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']
© www.soinside.com 2019 - 2024. All rights reserved.