在运行以下代码时
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
任何帮助将不胜感激。
大多数错误都不言自明。
你的列表usernames
被初始化为空,即长度为0.所以无论index
是什么整数,usernames[index]
都会尝试访问一个不存在的元素。这就是为什么你得到一个IndexError
。
你想要做的是将元素追加到列表usernames
。 append
方法做到了。所以你的for循环应该是:
for index in range(len(names)):
usernames.append(names[index].lower().replace(" ", "_"))
尝试阅读任何python-beginner关于列表的教程,或至少在继续之前阅读the official documentation。
试图设置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)
有很多方法可以使用下划线(_)获取List所有名称
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for index in names:
usernames.append(index.replace(" ", "_"))
print(usernames)
usernames.append(index.lower().replace(" ", "_"))
试试这个优化的代码:
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']