【问题标题】:How to compare number of values in a dictionary [closed]如何比较字典中值的数量[关闭]
【发布时间】:2019-08-31 01:12:23
【问题描述】:

我正在尝试比较字典中的值的数量。 另外,我希望它被排序

dic = {x: {(1,2),(3,4)}, y:{(1,2)}}

我想看看

[('x',2),('y',1)]

我正在使用 lambda,但我无法弄清楚。

【问题讨论】:

标签: python dictionary


【解决方案1】:

您可以使用列表推导式和dict.items:

>>> dic = {"x": {(1, 2), (3, 4)}, "y": {(1, 2)}}
>>> [key: len(val) for key, val in dic.items()]
[('x', 2), ('y' ,1)]

【讨论】:

    【解决方案2】:

    假设您的输入如下所示:dic={x:[a,b],y:[c]}。试试这个,

    res=sorted([(x,len(dic[x])) for x in dic],key=lambda x:x[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 2019-09-09
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      相关资源
      最近更新 更多