キーの【パイソン】スキル取得した辞書(以上)の最大値(値)(キー)

要約すると、以下の4つのケースに分けます:

  • ケース1:唯一の最大値を、取得した唯一最大値(値)は、キー(鍵)に対応
  • ケース2:唯一の最大値、最大値(値)と対応するキー(鍵)を取得中
  • 三つの場合:最大値は、複数のキーに対応する全ての取得(値)の最大値(キー)
ケース1:唯一の唯一最大の最大結合を得ます

方法の一つ:使用GET

>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3}
>>> print(max(dict, key=dict.get))
four

方法2:ラムダ匿名関数

>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3}
>>> print(max(dict, key=lambda i: dict[i]))
four

方法3:演算子機能モジュールitemgetter

>>> import operator
>>>
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3}
>>> print(max(dict.items(), key=operator.itemgetter(1))[0])
four

どの次元データ、以下に示すオブジェクトの数、のシリアル番号を取得するためのモジュールitemgetterオペレータ関数パラメータ:

>>> import operator
>>>
>>> a = [1, 2, 3, 4]
>>> b = operator.itemgetter(0)  # 定义函数b,获取对象的第0个域的值
>>> print(b(a))
1
>>> b = operator.itemgetter(0, 1) # 定义函数b,获取对象的第0个和第1个域的值
>>> print(b(a))
(1, 2)
ケース2:唯一の最大値、最大値を取得し、キーは、に対応して

方法:演算子機能モジュールitemgetter

>>> import operator
>>>
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3}
>>> print(sorted(dict.items(), key=operator.itemgetter(1), reverse=True)[0])
('four', 4)

方法2:ジップ方法

>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3}
>>> print(max(zip(dict.values(), dict.keys())))
(4, 'four')
ケース3:全ての結合の最大値を取得するために、複数の最大値があります
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3, 'four_1': 4}
>>> max_list = []
>>> max_value = max(dict.values())  # 利用 max 函数先找到最大 value
>>> for m, n in dict.items():       # 遍历字典一遍找对应的 key 值
	if n == max_value:
		max_list.append(m)

>>> print(max_list)
['four', 'four_1']
149元記事公開 ウォンの賞賛518 ビューに46万+を

おすすめ

転載: blog.csdn.net/qq_36759224/article/details/104364007