![](/img/trans.png)
[英]Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys
[英]Pythonic way to fetch all elements in a dictionary, falling between two keys?
我有一個字典對象,我想提取字典的一個子集(即返回另一個字典),其中包含密鑰與特定條件匹配的父字典的所有元素。
例如:
parent_dict = {1: 'Homer',
2: 'Bart',
3: 'Lisa',
4: 'Marge',
5: 'Maggie'
}
def filter_func(somedict, key_criteria_func):
pass
我想寫(以filter_func
方式), filter_func
,以便我可以像這樣調用它:
filter_func(parent_dict, ">2 and <4")
這將返回新的字典:
{ 3: 'Lisa' }
編寫filter_func?
的最filter_func?
方法是filter_func?
為了簡單起見,我將標准限制為簡單的布爾運算。
[[編輯]]
這是我嘗試以下命令時的輸出:
>>> {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
File "<stdin>", line 1
{key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
^
SyntaxError: invalid syntax
順便說一下,我正在運行Python 2.6.5
解
從python 2.7開始,您可以使用字典理解。 有類似列表推導,但應用於字典:
>>> parent_dict = {1: 'Homer',
... 2: 'Bart',
... 3: 'Lisa',
... 4: 'Marge',
... 5: 'Maggie'
... }
>>> {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
1: {3: 'Lisa'}
您可能不需要將其作為函數,但如果這樣做,您可以使用lambda函數作為過濾器:
>>> def filter_func(somedict, key_criteria_func):
... return {k:v for k, v in somedict.iteritems() if key_criteria_func(k)}
...
... filter_func(parent_dict, lambda x: 2 < x < 4)
2: {3: 'Lisa'}
對於Python 2.6.5和2.7之前的所有版本,將dict理解替換為:
dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)
為什么lambda功能?
Lambda函數不是魔術,它只是一種輕松創建動態的方法。 你可以用lambda
做你所做的一切,唯一的區別是lambda是表達式,因此可以在parenthis之間直接使用。
相比:
>>> func = lambda x: 2 < x < 4
>>> func(3)
True
附:
>>> def func(x):
... return 2 < x < 4
...
>>> func(3)
True
它完全相同並產生相同的功能,除了lambda函數沒有名稱。 但你不在乎,在你的情況下你不需要名字,你只需要一個引用來調用它,變量func
包含這個引用。
lambda語法很奇怪,因為:
def var(param):
但var = lambda param:
. 沒有什么神奇的,它只是語法 lambda
:返回結果必須適合一條指令。 return
關鍵字:lambda的右邊部分是自動返回的 現在lamda的好處是,因為它是一個表達式,你可以在括號之間使用它,這意味着你可以同時創建和傳遞你的功能。
相比:
>>> filter_func(parent_dict, lambda x: 2 < x < 4)
附:
>>> def func(x):
... return 2 < x < 4
...
>>> filter_func(parent_dict, func)
它完全一樣。 lambda只是更短。
這里最難的部分是要理解你可以在Python中將函數作為參數傳遞,因為Python中的所有東西都是一個對象,包括函數。
你甚至可以這樣做:
>>> def func():
... print "test"
...
>>> ref_to_func = func # assign the function refence to another var
>>> del func # delete this label
>>> ref_to_func() # call the function from this label
test
你甚至可以在一行上定義一個函數:
>>> def func(): print "test"
>>> func()
test
但你不能這樣做:
filter_func(parent_dict, def func(x): 2 < x 4 )
lambda是有用的。
dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)
這適用於Python 2.6.5。
對於python 2.5.2:
dict( (k,v) for k,v in parent_dict.iteritems() if k > 2 and k < 4 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.