Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python list.remove()不工作_Python_Regex_List - Fatal编程技术网

Python list.remove()不工作

Python list.remove()不工作,python,regex,list,Python,Regex,List,我使用了一个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_lis

我使用了一个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_list = dir(commands)
for com in commands_list:
   if re.match('__.+__', com):
      commands_list.remove(com)
   else:
      pass
我希望主脚本列出commands.py中的函数,因此我使用了
dir(commands)
,它提供了以下输出:

然后,我尝试使用正则表达式删除包含“\uuuu”的项,如下所示:

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_list = dir(commands)
for com in commands_list:
   if re.match('__.+__', com):
      commands_list.remove(com)
   else:
      pass
这不管用。如果我尝试在没有for循环或正则表达式的情况下执行此操作,它会声明条目(我刚刚从print(列表)复制并粘贴的条目)不在列表中


作为第二个问题,我能让dir只列出函数而不是“datetime”吗?

我在这里只使用列表comp:

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

不能在迭代列表时修改列表,请改用列表理解:

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

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

您可以
筛选列表:

commands_list = filter(lambda cmd: not re.match('__.+__', cmd), dir(commands))
这将过滤掉所有与正则表达式不匹配的项。

使用,尝试以下操作:

[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']
使用以下方法也可以获得相同的结果:


不需要
regex
我不这么认为。
new\u lst=[item for item in lst if''uuuuuu'not in item]
我会在这里使用列表理解。
[I for I in dir(commands)if not(I.startswith('uuuuuu')和I.endswith('uuuuu')]
正确。这是实际问题。谢谢。关于'callable',
可调用'(commands.what_time_是什么?)
返回true,所以我尝试了以下方法:
commands_list=[com for com in commands_list if(not re.match(“'.+''.+'''.+'''.+com”)和callable('commands'.+com))
这不起作用,因为
callable('commands.'.+com)
总是返回false,即使
callable(commands.what_time是什么)
返回true,并且
com=what\u time\u it
@Alex这是因为您要向它传递一个字符串,所以必须像这样传递对象:
callable(getattr(commands,com))