【问题标题】:Python list.remove() not workingPython list.remove()不起作用
【发布时间】:2017-05-24 02:52:06
【问题描述】:

我包含一个 python 文件 commands.py 使用 导入命令

文件如下:

import datetime

def what_time_is_it():
    today = datetime.date.today()
    return(str(today))

def list_commands():
    all_commands = ('list_commands', 'what time is it')
    return(all_commands)

我希望主脚本列出 commands.py 中的函数,所以我使用了dir(commands),它给出了输出:

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'datetime', 'list_commands', 'what_time_is_it']

然后我尝试使用正则表达式删除包含'__'的项目,如下所示:

commands_list = dir(commands)
for com in commands_list:
   if re.match('__.+__', com):
      commands_list.remove(com)
   else:
      pass

这不起作用。如果我尝试在没有 for 循环或正则表达式的情况下执行此操作,它会声称该条目(我刚刚从 print(list) 复制并粘贴的条目不在列表中。

作为第二个问题,我可以让 dir 只列出函数,而不是“日期时间”吗?

【问题讨论】:

  • 不需要regex 我不认为。 new_lst = [item for item in lst if '__' not in item]
  • 我会在这里使用列表理解。 [i for i in dir(commands) if not (i.startswith('__') and i.endswith('__'))]

标签: python regex list


【解决方案1】:

您不能在迭代时修改列表,请改用列表推导:

commands_list = dir(commands)
commands_list = [com for com in commands_list if not re.match('__.+__', com)]

作为第二个问题,您可以使用callable 检查变量是否可调用。

【讨论】:

  • 正确。这是真正的问题。
  • 这行得通,谢谢。关于“可调用”,callable(commands.what_time_is_it) 返回 true,所以我尝试了以下操作:commands_list = [com for com in commands_list if (not re.match('__.+__', com) and callable('commands.' + com))] 这不起作用,因为 callable('commands.' + com) 总是返回 false,即使 callable(commands.what_time_is_it) 返回 true,并且 com = what_time_is_it
  • @Alex 那是因为你传递一个字符串,你必须像这样传递对象:callable(getattr(commands, com))
【解决方案2】:

我会在这里使用一个列表组合:

commands_list = [cmd for cmd in commands_list if not (cmd.startswith('__') and cmd.endswith('__'))]

【讨论】:

    【解决方案3】:

    使用list comprehension,试试这个:

    [item for item in my_list if '__' not in (item[:2], item[-2:])]
    

    输出:

    >>> [item for item in my_list if '__' not in (item[:2], item[-2:])]
    ['datetime', 'list_commands', 'what_time_is_it']
    

    使用filter()可以达到同样的效果:

    filter(lambda item: '__' not in (item[:2], item[-2:]), my_list)  # list(filter(...)) for Python 3
    

    【讨论】:

      【解决方案4】:

      您可以filter列表:

      commands_list = filter(lambda cmd: not re.match('__.+__', cmd), dir(commands))
      

      这会过滤掉所有 not 匹配正则表达式的项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-21
        • 2018-05-21
        相关资源
        最近更新 更多