給定的
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
{'ref': 2, 'a': 4, 'b': 5, 'c': 6},
{'ref': 3, 'a': 7, 'b': 8, 'c': 9}]
讓我們考慮一個可置換整數串列
[7,8,9]=[7,9,8]=[8,7,9]=[8,9,7]=[9,7,8]=[9,8,7] # (3!)
這個串列中的每一個都有一個唯一的映射參考,那么(8,7,9)我怎么能得到ref=3呢?
同樣在實際情況下,我可能直到 10 (a,b,c,d,e,f,g,h,i,j)...
uj5u.com熱心網友回復:
您可以生成一個字典,將值映射frozenset到 ref 的值:
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
{'ref': 2, 'a': 4, 'b': 5, 'c': 6},
{'ref': 3, 'a': 7, 'b': 8, 'c': 9}]
keys = ['a', 'b', 'c']
out = {frozenset(d[k] for k in keys): d['ref'] for d in listOfDict}
# {frozenset({1, 2, 3}): 1,
# frozenset({4, 5, 6}): 2,
# frozenset({7, 8, 9}): 3}
例子:
check = frozenset((8,7,9))
out[check]
# 3
但我事先不知道其他鍵的名稱!
然后使用這種方法:
out = {}
for d in listOfDict:
d2 = d.copy() # this is to avoid modifying the original object
out[frozenset(d2.values())] = d2.pop('ref')
out
或作為一種理解:
out = dict(((d2:=d.copy()).pop('ref'), frozenset(d2.values()))[::-1]
for d in listOfDict)
uj5u.com熱心網友回復:
這是您的問題的評論解決方案。我們的想法是在價值觀的排序串列進行比較a,b,c等與排序值list_of_ints。對于給定的一組數字的所有排列,排序后的值將相同。
def get_ref(list_of_ints):
# Loop through dictionaries in listOfDict.
for dictionary in listOfDict:
# Get list of values in each dictionary.
vals = [dictionary[key] for key in dictionary if key != "ref"]
if sorted(vals) == sorted(list_of_ints):
# If sorted values are equal to sorted list of ints, return ref.
return dictionary["ref"])
順便說一句,我相信通過以下方式將這些資料構建為 dicts 的 dict 會更清晰:
dicts = {
1: {'a': 1, 'b': 2, 'c': 3},
2: {'a': 4, 'b': 5, 'c': 6},
3: {'a': 7, 'b': 8, 'c': 9}
}
代碼將是:
def get_ref(list_of_ints):
for ref, dictionary in dicts.items():
if sorted(dictionary.values()) == sorted(list_of_ints):
return ref
假設排列中的所有整數都是唯一的,可以使用集合而不是排序串列進一步簡化代碼。
uj5u.com熱心網友回復:
由于它是一個 dict 串列,我可以使用 for 回圈呼叫每個 dict 并在 ref 上記錄第一個數字
for i in listOfDict:
ref_num=i["ref"]
并將字典變成串列,我們只需使用:
z=list(i.values())
然后最后一步是查找它是否與輸入串列相同,如果是,我們列印/回傳參考編號
if z[1:]==InputList:
return ref_num
代碼應該是這樣的:
listOfDict = [
{"ref": 1,
"a": 1,
"b": 2,
"c": 3},
{"ref": 2,
"a": 4,
"b": 5,
"c": 6},
{"ref": 3,
"a": 7,
"b": 8,
"c": 9},]
def find_ref_Num(InputList):
for i in listOfDict:
ref_num=i["ref"]
z=list(i.values())
if z[1:]==InputList:
return ref_num
print ("your ref number is: " str(find_ref_Num([7,8,9])))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404558.html
標籤:
下一篇:比較兩個單獨的JSON
