2012-04-15 78 views
1

快速問題?我想知道是否有pythonic方式來獲得以下。找到defaultdict中元素的數量(列表)python

我有一個defaultdict(名單)

foo = {"a":[1,2,3], "b":[3]....} and so on. 

有沒有寫返回我,只有其表有長度超過鍵一功能的Python的方式「N」

因此,例如

def return_keys_based_on_value_length(num,dictionary): 
    key_list = [] 
    for k,v in dictionary: 
     if len(v)>= num: 
      key_list.append(k) 
    return key_list 

有沒有一種pythonic的方式來做到這一點? 感謝

回答

4
foo = {"a":[1,2,3], "b":[3], "c":[1,2], "d":[1,2,3,4]} 

n = 2 

my_list = [key for key,val in foo.iteritems() if len(val) > n] 

結果:

>>> my_list 
['a', 'd'] 
1
n = 2 
foo = {"a":[1,2,3], "b":[3]} 
key_list = [item for item in foo.keys() if len(foo[item]) > 2] 

結果['a']

1

您可以嘗試使用的過濾器功能:

filter(lambda x: len(dictionary[x])> num, dictionary.keys()) 
+0

我不認爲過濾器是最好的Ť o如果您還需要它也可用於地圖。 – 2012-04-15 21:21:49

相關問題