【问题标题】:How to find maximum element from a list and its index?如何从列表及其索引中找到最大元素?
【发布时间】:2021-05-20 11:15:27
【问题描述】:

我有一个包含有序词典的列表。这些有序字典有不同的大小,也可以有相同的大小(例如,10 个字典的长度可以是 30,而 20 个字典的长度可以是 32)。我想从列表中找到字典的最大项目数。我已经尝试过了,这让我得到了正确的最大长度:

maximum_len= max(len(dictionary_item) for dictionary_item in item_list)

但是我怎样才能找到给出 maximum_len 的字典字段呢?假设 maximum_len 是 30,我还想打印 30 个键的字典。它可以是任何大小为 30 的字典,而不是特定的字典。我只需要那个字典的键。

【问题讨论】:

  • 请提供清单。
  • 列表是否已经按字典大小排序? “有序字典”是什么意思?

标签: python list dictionary key


【解决方案1】:

你总是可以使用过滤器:

output_dics=filter((lambda x: len(x)==maximum_len),item_list)

那么你有所有满足条件的字典,随机选择一个或第一个

【讨论】:

    【解决方案2】:

    不知道这是否是最简单或最优雅的方法,但您可以编写一个返回 2 个值的简单函数,即您已经计算的 max_length 以及您可以通过 .index 方法获得的 dict以及您正在搜索的对象的 max_length。

    我在谈论这样的事情:

        def get_max(list_of_dict):
            plot = []
            for dict_index, dictionary in enumerate(list_of_dict):
                plot.append(len(dictionary))
    
            return max(plot), list_of_dict[plot.index(max(plot))]
    
        maximum_len, max_dict = get_max(test)
    

    对其进行了测试,适用于我的情况,尽管我刚刚为自己制作了一个只有 5 个不同长度的 dicts 的测试列表。

    编辑: 将变量“dict”更改为“dictionary”,以防止它从外部范围隐藏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2015-10-24
      • 2020-12-05
      • 1970-01-01
      相关资源
      最近更新 更多