如何在Python字典中逐个弹出较大的值?
只留下值最小的键,我无法使用如何在Python字典中逐个弹出较大的值?,python,dictionary,Python,Dictionary,只留下值最小的键,我无法使用min()函数 移动OP从其评论中尝试的代码:- for i in key: if dictionary[i]<dictionary[key]: dictionary.pop(key) elif dictionary[i]==dictionary[key]: print (dictionary[i]) 对于i in键: 如果字典[i]你可以试试这个。它使用任何函数将每个键的值与除其自身值以外的所有其他值进
min()
函数
移动OP从其评论中尝试的代码:-
for i in key:
if dictionary[i]<dictionary[key]:
dictionary.pop(key)
elif dictionary[i]==dictionary[key]:
print (dictionary[i])
对于i in键:
如果字典[i]你可以试试这个。它使用任何
函数将每个键的值与除其自身值以外的所有其他值进行比较。如果找到任何小于该值的值,则弹出键
>>> my_dict = {1: 2, 2: 3, 3: 4}
>>> for key, value in my_dict.items():
if any(value > value1 for key1, value1 in my_dict.items() if key1 != key):
my_dict.pop(key)
3
4
>>> my_dict
{1: 2}
any
函数返回True
如果传递给它的列表中至少有一个值为True
例如:-
any([0, 0, False, True]) # Will print True
any([0, 0, False, False]) # Will print False
更新:-
any([0, 0, False, True]) # Will print True
any([0, 0, False, False]) # Will print False
如果您不想使用any
函数,可以将any
函数的for循环移到外部,并仅在该循环中执行测试:-
my_dict = {1: 2, 2: 3, 3: 4}
for key, value in my_dict.items():
for key1, value1 in my_dict.items():
if key1 != key and value > value1:
my_dict.pop(key)
print my_dict
可以使用dict.items()获取最小值函数
my_dic = {...}
print min(my_dic.item(), key = lambda x: x[1])[0]
听起来像是家庭作业。发布您所做的。对使用sorted
函数或sort
方法有任何限制吗?如果这是我的家庭作业,我想我对这本书的理解是完全错误的。@user1718826。。请张贴您在问题中尝试的代码。把它从评论中移开。我从来没有学过“任何”方法。我可以用一个循环来代替这个吗?@user1718826。。是的,你可以使用循环。您可以看到,我在任何
函数中使用了for
循环。把它移到外面,在里面做测试。您不需要任何函数。谢谢,如何避免在迭代过程中更改字典大小?@user1718826。。你需要使用另一本字典。移动字典中最小的元素。为此,您需要稍微更改代码。我让你试试看。