python - 删除列表中的字母和空格时出现问题

标签 python

我正在 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/

相关文章:

python - 基于 http Web 服务的简单 XML

Python:变量、继承和默认参数

python - 用街道号码和字母 python 分隔街道名称字符串

javascript - ( flask ,d3) Uncaught ReferenceError : d3 is not defined

php - 重新格式化 Excel 布局以适应 JSON

python - 协程 yield 与任务 yield

python - 如何编写正则表达式来捕获特定的数字格式并排除其余的?

python - 扩展模块

python - 如何扩展 Python 枚举?

python - Postgre 和pyodbc 的 bool 值不兼容?