[英]Is there an elegant way of combining the Python vars() and filter() functions to display the values of a subset of variables?
有沒有辦法在字符串中顯示變量子集的名稱和值?
下面過濾了某些變量的名稱,但是否有一種優雅的方式在一行中也顯示變量的值?
>>> result=list(filter(lambda x : x in ['a'], vars()))
>>> result
['a']
是的,可以這樣做:
>>> a = 123
>>> result = list(filter(lambda x: x[0] in {'a'}, vars().items()))
>>> result
[('a', 123)]
但更優雅的方式是使用列表推導式:
>>> a = 123
>>> result = [(name, value) for name, value in vars().items() if name in {'a'}]
>>> result
[('a', 123)]
使用vars().items()
獲取鍵和值。
但是你不能使用filter()
因為
result = list(filter(lambda x: x[0] in ['a'], vars().items()))
這將返回
[('a', 'value_of_a')]
到目前為止我管理的最好的事情:
foodict = {k: v for k, v in vars().items() if k in ['a']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.