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

时间:2019-03-13 03:56:56

标签: python

运行以下代码时

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

有很多方法可以用下划线(_)列出所有名称

  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(" ", "_"))

答案 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']