在交互模式下工作,我输入以下作业:
item = ['keys', 'values', 'items']
get = ['get', 'setdefault']
pop = ['pop', 'popitem']
copy = ['copy', 'fromkeys']
update = ['update']
clear = ['clear']
# my intent result
{'item': ['keys', 'values', 'items'],
'get': ['get', 'setdefault'],
'pop': ['pop', 'popitem'],
'copy': ['copy', 'fromkeys'],
'update': ['update'],
'clear': ['clear']}}
我打算通过词典理解和类型检查从locals()
获取它们的词典。
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'item': ['keys', 'values', 'items'], 'get': ['get', 'setdefault'], 'pop': ['pop', 'popitem'], 'copy': ['copy', 'fromkeys'], 'update': ['update'], 'clear': ['clear']}
我的代码:
{k:v for k, v in locals().items if isinstance(v, list)}
TypeError: 'builtin_function_or_method' object is not iterable
我修好了
In [12]: {k:locals[k] for k in locals() if isinstance(locals()[k], list)}
#Error reports again.
KeyError: '__name__'
如何解决?
答案 0 :(得分:4)
通过调用方法items()
:
{k:v for k, v in locals().items() if isinstance(v, list)}
编辑: 使用像这样的locals()听起来像一个丑陋的黑客,可以在交互模式下使用它来发现python如何存储它的变量,但在“真实代码”中使用它绝对不是一个好主意。如果您需要将这些参数存储在一起,请考虑一个类,例如:
class MyKeywords:
def __init__(self):
self.item = ['keys', 'values', 'items']
self.get = ['get', 'setdefault']
self.pop = ['pop', 'popitem']
self.copy = ['copy', 'fromkeys']
self.update = ['update']
self.clear = ['clear']
或者找到另一种方式来获取/存储它们,本地人绝对不是为此做的:)