Given是包含集合的列表的字典。找到集合中元素第一次出现的相应键的有效方法是什么?这应该针对字典中的所有独特元素来完成。
set()
[]
。集合在列表中的位置无关。只有关键是感兴趣的。
字典按其关键值按顺序排序。应按顺序搜索字典。
d
和元素
510
。答案是对于键343
,此元素首先出现在
d
中。对于
d
的集合中的所有值,都重复此操作。
d={
100: [{406, 491, 440, 448},{590, 633, 560, 564, 651, 681}],
343: [{366, 412, 440}, {448, 491, 510}, {557, 560, 544, 564, 633, 681}],
423: [{440, 448, 491, 510, 544, 557, 564, 681}],
433: [{412, 440, 448, 491},{536, 544, 510, 557, 560, 564}],
493: [{1286, 1285, 1357}]
}
我尝试了什么
这是一个有效的解决方案。它是使用3个循环天气的。
first_appearance = {}
for key, sets in d.items():
for s in sets:
for element in s:
if element not in first_appearance:
first_appearance[element] = key
# Display the result
print("[element,key]")
for element, key in first_appearance.items():
print(f"[{element},{key}], ",end="")
输出:
[element,key]
[440,100], [491,100], [406,100], [448,100], [560,100], [633,100], [564,100], [681,100], [651,100], [590,100], [412,343], [366,343], [510,343], [544,343], [557,343], [536,433], [1285,493], [1357,493], [1286,493],
我会以基本方式走:
for key, sets_list in d.items():
for sets in sets_list:
if target_number in sets:
return key
return None