如何从列表列表中获得最长的列表和总体最大值?

给出一个列表列表,我想找到最长的列表,以及所有列表的总最大值。被限制为不使用max(),我该怎么做?

我的尝试如下所示:

def newMax(table):
    a=-1
    if len(table) == 0:
        print("The list is empty")
    for i in range(len(table)*2):
        a+=1
        if i+1 >= len(table):
            print("Big number")
            break
        else:
            if len(table[a]) < len(table[a+1]):
                maxs=a+1
                if maxs < len(table[a+2]):
                    maxs = a + 2
                    print("test",table[maxs])
                    if maxs < len(table[a + 3]):
                        maxs = a + 3
                        print("test",table[maxs])

newMax([[1,3,1,5,51,15],[0,4,5],[1,2,3],5]])
fangke45 回答:如何从列表列表中获得最长的列表和总体最大值?

要找到

  1. 所有列表中的最大值,
  2. 最长的名单,

仅遍历所有列表,同时跟踪到目前为止遇到的最大值。

def newMax(table):

    maxValue = table[0][0]
    longestList = table[0]
    longestListLen = len(table[0])

这将到目前为止遇到的最大值设置为第一个列表的第一个元素,并将最长的列表设置为第一个列表。然后,我们遍历其余列表,以查看是否存在较大的值/较长的列表。

    for row in table: # iterate through all lists
        for val in row: # iterate through each value in each list
            if val > maxValue: # encountered a greater value
                maxValue = val # let's save the new biggest value

        rowLen = len(row) # get this list's length
        if len(row) > longestListLen: # encountered a longer list
            longestListLen = rowLen # save this list as the longest list
            longestList = row

现在,您拥有maxValue中所有列表的最大值和longestList中最长的列表。

,

将所有条目放在单个集合中,然后取最大的。这样,所有循环都发生在C端,如此高效:

def newMax(table):
    s = set()
    for l in table:
        s.update(l)
    return max(s)

根据上面和下面的注释,获取所有单个最大值,而不使用内置的max(),同时保持时间线性并且不编写超级嵌套函数:

import heapq

def newMax(table):
    maxvalues = list()
    for l in table:
        heapq.heapify(l)
        maxvalues.append(heapq.nlargest(1,l)[0])
    mv2 = maxvalues[:]
    heapq.heapify(mv2)
    return heapq.nlargest(1,mv2)[0],maxvalues

由于目标/要求似乎又在注释中发生了变化,因此又出现了

def newMax(table):
    length_max = -1
    max_length_list = None
    value_max = -2**31
    for l in table:
        if len(l) > length_max:
            length_max = len(l)
            max_length_list = l
        for i in l:
            if i > value_max:
                value_max = i
    return value_max,max_length_list
,

不确定您是否已经学习了递归,这是基于递归的解决方案,因为我不确定您的输入列表中可以包含多少级

input = [[1,3,1,5,51,15],[0,4,5],[1,2,3],5]]

def findMaxRec(input):
    max = -999999999
    for i in input:
        if isinstance(i,list):
            temp = findMaxRec(i)
            if temp > max:
                max = temp
        else:
            if i > max:
                max = i
    return  max

print(findMaxRec(input))
本文链接:https://www.f2er.com/3070439.html

大家都在问