我正在 python 中创建一个命令,该命令接受一条消息并将其转换为一个列表,然后删除前 5 个字母 (!calc)。然后,它检查列表中的每个项目是否是字母或空格。如果是,则将其从列表中删除。
换句话说,如果它收到消息“!calc abcdef”,我希望它打印“[]”(什么也没有)。
相反,我得到“['a', 'c', 'e']
message = "!calc abcdef"
if message.startswith("!calc"): #checks if the message starts with !calc
msg = list(message)
del msg[0:5] #deletes the !calc part
for i in msg: #goes through each item [" ", "a", "b", "c", "d", "e", "f"]
if (i.isalpha()) == True: #checks if the item is a letter
msg.remove(i) #removes the letter
elif (i.isspace()) == True: #checks if the item is a space
msg.remove(i) #removes the space
print(msg)
最佳答案
出现问题的原因是您在遍历列表时删除了列表中的项目。当您执行 for i in msg
时,您实际上可能会跳过一些元素。观察这段代码:
L = [1, 2, 3, 4, 5]
for i in L:
print(i)
if i % 2 == 0:
L.remove(i)
您可能期望 print
语句打印所有五个元素 1..5,但实际上它打印:
1
2
4
要解决此问题,您可以向后迭代数组,或使用列表理解:
msg = [i for i in msg if i.isalpha() == False or i.isspace() == False]
<小时/>
当然,您的整个代码也可以使用以下语法在一定程度上进行清理:
message = ''.join([i for i in message[:5] if not i.isalpha() and not i.isspace()])
关于python - 删除列表中的字母和空格时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347613/