简体   繁体   中英

How to find smallest sub-list in a list of list that also includes integers

Basically, i have a board of size N (lets say 4) with the biggest elements inside also of size N. I need to find the length of the smallest list in each row like in the following example: row = [[1, 2, 4], [1, 2, 4], 3, [1, 2]] should return the length of [1,2] and the index of that sublist but it returns an error because 3 is before it

I've written this

def full(puzzle):
    min = 0
    for i in range(len(puzzle)):
           for j in range(1 ,len(puzzle)):
               if isinstance(puzzle[i][j] , list):
                   if len(puzzle[i][j-1]) < len(puzzle[i][j]):
                       min = len(puzzle[i][j-1])
                       pos = (i , j-1)
    return pos

But the code doesnt work when j-1 is not a list. How would i make it so the function would compare the length of puzzle[i][j] to j-2, (or 3 if j-1 and j-2 are also not lists etc..)

edit: and since row is in board, id love for the code to return the index of both the row and column.

Try using the key attribute of min somehow like this

row = [[1, 2, 4], [1, 2, 4], 3, [1, 2]]
def func(item):
    return len(item) if type(item)==list else 999
sublist=min(row,key=func)
print('index of smallest list=',row.index(sublist))
print('length of smallest list=',len(sublist))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM