Python 删除列表中的字母和空格时出现问题
我正在用python编写一个命令,它接收一条消息并将其转换为一个列表,然后删除前5个字母(!calc)。然后,它检查列表中的每个项目是字母还是空格。如果是,则将其从列表中删除 换句话说,如果它收到消息“!calc abcdef”我希望它打印“[]”(无) 相反,我得到的是“['a','c','e']Python 删除列表中的字母和空格时出现问题,python,Python,我正在用python编写一个命令,它接收一条消息并将其转换为一个列表,然后删除前5个字母(!calc)。然后,它检查列表中的每个项目是字母还是空格。如果是,则将其从列表中删除 换句话说,如果它收到消息“!calc abcdef”我希望它打印“[]”(无) 相反,我得到的是“['a','c','e'] message = "!calc abcdef" if message.startswith("!calc"): #checks if the message starts with !calc
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)
出现此问题的原因是,您在遍历列表时正在删除列表中的项目。当您对msg中的i执行
操作时,实际上可能会跳过某些元素。请注意以下代码:
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()])
我猜是重复的,但这个问题在解释问题发生的原因方面很差