這是我練習的問題:
撰寫一個名為 is_1_to_1 的函式,它接受一個字典,其鍵和值都是字串作為引數,如果沒有兩個鍵映射到相同的值,則回傳 True。
我得到了這個:
def is_1_to_1(dic):
for value_1 in dic.values():
for value_2 in dic.values():
check_list = []
if value_2 == value_1 :
check_list.append(value_2)
else:
pass
if check_list != dic:
return (f"Dictionary: {dict.items(dic)} does not have unique entries.")
else:
return (f"DIctionary: {dict.items(dic)} does have unique entries.")
dic_1 = {"Marty": "206-9024", "Hawking": "123-4567",
"Smith": "949-0504", "Newton": "123-4567"}
dic_2 = {"Marty": "206-9024", "Hawking": "555-1234",
"Smith": "949-0504", "Newton": "123-4567"}
print(is_1_to_1(dic_1))
print(is_1_to_1(dic_2))
它回傳:
Dictionary: dict_items([('Marty', '206-9024'), ('Hawking', '123-4567'), ('Smith', '949-0504'), ('Newton', '123-4567')]) does not have unique entries.
Dictionary: dict_items([('Marty', '206-9024'), ('Hawking', '555-1234'), ('Smith', '949-0504'), ('Newton', '123-4567')]) does not have unique entries.
uj5u.com熱心網友回復:
你的錯誤很少。
比較
check_list != dic是無用的,因為它總是會給出True。你應該檢查是否check_list為空if not check_list:您創建
check_list內部for回圈,因此它用新的空串列替換它,如果最后一個元素不同,您可能會得到空串列。你比較相同的值 - 比如
dict["Marry"] == dict["Marry"]- 所以你總是在check_list. 你應該先檢查key1 != key2有問題,
... and return True但你總是回傳字串。
因為not check_list賦予True或False因此它可以降低到 回傳(不check_list)`
def is_1_to_1(dic):
check_list = []
for key1, val1 in dic.items():
for key2, val2 in dic.items():
if key1 != key2 and val1 == val2 :
check_list.append(val2)
#if not check_list: # check if empty
# return True
#else:
# return False
# shorter
return (not check_list)
# --- main ---
dic_1 = {
"Marty": "206-9024",
"Hawking": "123-4567",
"Smith": "949-0504",
"Newton": "123-4567",
}
dic_2 = {
"Marty": "206-9024",
"Hawking": "555-1234",
"Smith": "949-0504",
"Newton": "123-4567",
}
print(is_1_to_1(dic_1))
print(is_1_to_1(dic_2))
你也可以把它減少到
def is_1_to_1(dic):
for key1, val1 in dic.items():
for key2, val2 in dic.items():
if key1 != key2 and val1 == val2 :
return False # exit on first matching element
# after checking all elements
return True
uj5u.com熱心網友回復:
通常有許多不同的方法可以解決一個問題。對此的快速解決方案可能很簡單:
def is_1_to_1(dic):
values = dic.values()
return len(values) == len(set(values))
Pythonset只包含唯一值。因此,如果長度不同,則意味著原始 dict 值集包含重復項。
作為旁注,由于比較,您的代碼無法成功:
if check_list != dic:
正如您撰寫的那樣,它check_list是一個陣列,并且dic是一個字典。所以他們永遠不會真正匹配,這種比較永遠是真的。此外,與使用,通過字典值串列回圈兩次邏輯,你將最終check_list僅僅是相同的dic.values()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358758.html
上一篇:減少多個鍵的相同值的字典大小?
