繁体   English   中英

Python list.remove()无法正常工作

[英]Python list.remove() not working

我使用导入命令包括了一个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)复制并粘贴的条目不在列表中。

作为第二个问题,我能否仅从目录中列出函数,而不要列出“ datetime”?

迭代时无法修改列表,而应使用列表理解:

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

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

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

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

使用列表理解 ,请尝试以下操作:

[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

您可以filter列表:

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

这将筛选出所有与正则表达式not匹配的项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM