2017-02-09 53 views
-2

爲了創建一個函數,在稍後創建另一個函數時,我正在使用字典和鍵。通過這種方式,我一直在搜索一些關於它們如何工作的信息。但是當我必須使用字典和if語句時,我通常會卡住。尋找最好的if語句結構

我在一個函數中工作,該函數返回字典中也是字典中鍵的數量。我的第一個想法是使用for循環,但是我陷入了if語句代碼中。這似乎是錯誤的,但我不知道可能是什麼。我推斷我必須使用一個in運算符和變量k和d,並且還有一個索引,但我不知道我是否正確使用它們。 任何幫助將是有用的。 在此先感謝

這是我目前的進度:

def count_values_that_are_keys(d): 
'''(dict) -> int 

Return the number of values in d that are also keys in d. 

>>> count_values_that_are_keys({1: 2, 2: 3, 3: 3}) 
3 
>>> count_values_that_are_keys({1: 1}) 
1 
>>> count_values_that_are_keys({1: 2, 2: 3, 3: 0}) 
2 
>>> count_values_that_are_keys({1: 2}) 
0 
''' 

result = 0 
for k in d: 
    if [d in [k]]: # This part it seems wrong cause I don't get what I expect 
     result = result + 1 

return result 
+0

請正確縮進Python代碼。否則,你會在人們爲你閱讀的代碼中引入新的問題。 – khelwood

回答

1
def count_values_that_are_keys(d): 
    return sum([x in d.keys() for x in d.values()]) 

使用列表理解構建具有True/False列表。總和將True視爲1和False視爲0.

+1

......你不知道我有多接近編寫'def obligatory_list_comprehension_method()':P Upvote雖然,它絕對是一個更清潔的方法。 – roganjosh

+0

謝謝!對大多數情況來說,這應該足夠了。如果確實需要,可以使用集合優化成員測試。 –

+1

是的,我從來沒有真正考慮過使用'set'這種東西的尺寸方面的轉折點。它可能不像我想象的那麼高,但肯定不值得在這裏。 – roganjosh

1

的東西,如您目前的做法堅持,它更容易只是爲了讓字典鍵的列表,然後查了字典值的成員在該列表。對於大型字典,您希望使用dict_keys = set(d.keys())來加快查找速度。

def count_values_that_are_keys(d): 
    '''(dict) -> int 

    Return the number of values in d that are also keys in d. 

    >>> count_values_that_are_keys({1: 2, 2: 3, 3: 3}) 
    3 
    >>> count_values_that_are_keys({1: 1}) 
    1 
    >>> count_values_that_are_keys({1: 2, 2: 3, 3: 0}) 
    2 
    >>> count_values_that_are_keys({1: 2}) 
    0 
    ''' 

    dict_keys = d.keys()  

    result = 0 
    for key, value in d.items(): 
     if value in dict_keys: 
      result += 1 

    return result 

print(count_values_that_are_keys({1: 2, 2: 3, 3: 3})) 
print(count_values_that_are_keys({1: 1})) 
print(count_values_that_are_keys({1: 2, 2: 3, 3: 0})) 
print(count_values_that_are_keys({1: 2})) 
+0

哦,我不知道那種方法。是否有任何方法通過使用in運算符和變量k和d來編寫if語句,還有一個索引?我的意思是這可能嗎?就是想。不管怎麼說,還是要謝謝你。 – hugo

+1

@hugo我不是很清楚你在問什麼,但你不能索引字典,因爲它有[沒有固定順序](http://stackoverflow.com/questions/15479928/why-is-the-order-在-字典和集 - 任意)。如果您覺得這些答案中的任何一個都解決了您的問題,請考慮[標記爲已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),以便問題已經結束。 – roganjosh