[英]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.