运行以下代码时
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
任何帮助将不胜感激。
答案 0 :(得分:0)
有很多方法可以用下划线(_)列出所有名称
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(" ", "_"))
答案 1 :(得分: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']