代码之家  ›  专栏  ›  技术社区  ›  Jazzmine

如何在列表列表(嵌套列表包含字符串和数字)中找到具有最大值的列表?

  •  5
  • Jazzmine  · 技术社区  · 7 年前

    list_of_lists = [['a',1,19,5]['b',2,4,6],['c',22,5,9],['d',12,19,20]]
    

    max(list_of_lists) 会回来的

    [['c',22, 5,9],['d',12,19,20],['a',1,19,5]]
    

    或者如果我在循环 list_of_lists 我可以根据所选列表的索引,将每个具有前x max值的列表附加到另一个列表列表中。

    下面是我正在使用的代码,但它有缺陷,因为我认为我需要删除每个循环末尾的选定答案,这样它就不会出现在下一个循环中,它只会查看第4列(x[3])

    for y in case_list:
        last_indices = [x[3] for x in case_list]
        print("max of cases is: ",max(last_indices))
    

    目前的结果是:

    max of cases is:  22
    max of cases is:  22
    max of cases is:  22
    

    这个 answer

    这个 answer 给出单个列表中的前x个最大值。

    1 回复  |  直到 7 年前
        1
  •  4
  •   benvc    7 年前

    如果嵌套列表在第一个索引处总是只有一个字符串(如示例中所示),则可以使用 max() 在每个嵌套列表(不包括第一项)的切片上。然后,只需根据您想要的“top”结果的数量对最终输出进行切片。下面是获取具有最大值的“前”3个列表的示例。

    list_of_lists = [['a',1,19,5],['b',2,4,6],['c',22,5,9],['d',12,19,20]]
    
    # sort nested lists descending based on max value contained
    sorted_list = sorted(list_of_lists, key=lambda x: max(x[1:]), reverse=True)
    
    # slice first 3 lists (to get the "top" 3 max values)
    sliced_list = sorted_list[:3]
    
    print(sliced_list)  
    # OUTPUT
    # [['c', 22, 5, 9], ['d', 12, 19, 20], ['a', 1, 19, 5]]
    

    def max_lists(data, num):
        results = sorted(data, key=lambda x: max(x[1:]), reverse=True)
        return results[:num]
    
    list_of_lists = [['a',1,19,5],['b',2,4,6],['c',22,5,9],['d',12,19,20]]
    
    top_three = max_lists(list_of_lists, 3)
    
    print(top_three)                     
    for x in top_three:
        print(f'max value: {max(x[1:])} list: {x}')
    
    # OUTPUT
    # [['c', 22, 5, 9], ['d', 12, 19, 20], ['a', 1, 19, 5]]
    # max value: 22 list: ['c', 22, 5, 9]
    # max value: 20 list: ['d', 12, 19, 20]
    # max value: 19 list: ['a', 1, 19, 5]