【问题标题】:Select key from dictionary after sorting it by both value criteria and key criteria按值标准和键标准排序后从字典中选择键
【发布时间】:2020-10-11 13:35:18
【问题描述】:

dict (在 Python 2.7 中),如果一阶排序标准有多个相等的值,我如何选择其值按多个条件排序的键? p>

my_dict = {' A': 0.6, 'AB': 0.6, 'ABC': 0.4}

我当前的代码将选择键 A,因为它在具有最高值 0.6 的项目列表中排名第一。

my_key = max(my_dict.iteritems(), key=operator.itemgetter(1))[0]

但是,当有多个具有相同值的键(0.6)时,我不想选择具有最高值的第一项,而是按键的字符串长度其次排序 去除空格之后。

所以在伪代码中,我正在寻找能够达到效果的东西:

my_key = max(my_dict.iteritems(), keys=[highest_value, longest_key_str_length_after_strip])[0]

这将给出密钥AB,因为当两个值都是0.6 时计算len(x.strip()) 时,它的密钥长度比 A 长。

问题:如何通过Python 2中的一些排序功能来实现上述功能,即性能好?通过自定义函数类似于max()


Pandas 类比示例

举个具体的例子,我在 Pandas 中制作了一个模拟解决方案,它完成了上述任务——但是为此目的创建 DataFrame 似乎是资源密集型的,因为我做了这个操作很多 许多词典的次数:

import pandas as pd

df = pd.DataFrame(my_dict.items(), columns=['Key', 'Value']) #Create DataFrame from dict.

df['Key_Strip_Len'] = df['Key'].str.strip().str.len()        #Create new column w/ string lengths of stripped keys.

print df:

        Key      Value    Key_Strip_Len
0      " A"       0.6                 1
1      "AB"       0.6                 2
2      "ABC"      0.4                 3
df = df.loc[df['Value'] == df['Value'].max()]                #Keep only rows that have the highest value.

df = df.sort_values(by=['Key_Strip_Len'], ascending=False)   #Sort DataFrame by highest key string length.

my_key = df['Key'].values[0]                                 #Choose key in first row of column 'Key'.

print df:

        Key      Value    Key_Strip_Len
1      "AB"       0.6                 2
0      " A"       0.6                 1

还有my_key == AB

【问题讨论】:

    标签: python python-2.7 sorting


    【解决方案1】:

    一个元组可以用来打破关系:

    my_dict = {' A': 0.6, 'AB': 0.6, 'ABC': 0.4}
    
    greatest = max(my_dict.items(), key=lambda kv: (kv[1], len( kv[0].strip() )))
    print(greatest)
    

    输出:

    ('AB', 0.6)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多