我有一个名为 cdc_year_births 的 Python 字典。
对于 cdc_year_births,键是单位(在本例中单位是年),值是该单位的出生人数:
print(cdc_year_births)
{2000: 4058814, 2001: 4025933, 2002: 4021726, 2003: 4089950, 1994: 3952767,
1995: 3899589, 1996: 3891494, 1997: 3880894, 1998: 3941553, 1999: 3959417}
我写了一个函数来返回最大和最小年份以及他们的出生。当我启动该函数时,我想我应该将最大和最小单位分别硬编码为 0 和 1000000000,然后遍历字典并将每个键的值与这些硬编码值进行比较;如果满足条件,我将替换最大/最小单位和最大/最小出生时间。
但是如果我使用的字典有负值或大于 1000000000 的值,这个函数将不起作用,这就是为什么我必须在第一个循环中从字典中“加载”一些实际值,然后循环遍历它们再次。
我构建了这个函数,但无法让它正常工作:
def max_min_counts(data):
max_min = {}
for key,value in data.items():
max_min["max"] = key,value
max_min["min"] = key,value
for key,value in data.items():
if value >= max_min["max"]:
max_min["max"]=key,value
if value <= max_min["min"]:
max_min["min"]=key,value
return max_min
t=max_min_counts(cdc_year_births)
print(t)
它导致 TypeError: unorderable types: int() >= tuple() for
if value >= max_min["max"]:
和
if value <= max_min["min"]:
我尝试按照 Finding the max and min in dictionary as tuples python 中的描述从元组中提取值,但无法使其正常工作。
谁能帮我实现第二个较短的函数,或者告诉我如何编写更好的函数?
非常感谢您。
最佳答案
您的值是二元组。您需要进一步的索引级别才能使它们正常工作:
if value >= max_min["max"][1]:
还有,
if value <= max_min["min"][1]:
如果你想预设最大/最小值,你可以使用 float('inf')
和 -float('inf')
:
max_min["max"] = (-1, -float('inf')) # Smallest value possible.
max_min["min"] = (-1, float('inf')) # Largest value possible.
您可以使用 max
、min
和 operator.itemgetter
高效地执行此操作以避免 lambda
:
from operator import itemgetter
max(cdc_year_births.items(), key=itemgetter(1))
# (2003, 4089950)
min(cdc_year_births.items(), key=itemgetter(1))
# (1997, 3880894)
这是使用 reduce
计算最大最小值的巧妙方法
from fuctools import reduce
reduce(lambda x, y: x if x[1] > y[1] else y, cdc_year_births.items())
# (2003, 4089950)
reduce(lambda x, y: x if x[1] < y[1] else y, cdc_year_births.items())
# (1997, 3880894)
items()
从您的字典中生成一个元组列表,key
告诉函数在选择最大值/最小值时要比较的对象。
关于python - 从包含元组值的字典中查找最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449505/