Preeti Deshpande
Preeti Deshpande

Reputation: 21

find sum and minimum of nested list

How do we calculate with having both int element and list of list element.

def minelementNested(list):
    minele = list[0]
    sumele = 0
    count = 0
    for i in list1:
        if type(i) is int:
            sumele = sumele+i
            if i < minele:
                minele = i
            count = count +1
        else:
            sumele += sum(i)
            count = count + len(i)
            else_min = min(i)
            if else_min < minele:
                minele = else_min
    avg = sumele/count
    print(avg)
    return minele

list1 = [23,24,[10,11,12],56,85,[34,45,6]]
minelementNested(list1)

Is there any other way to do this? or can we convert the individual int element to list and go ahead with list comprehension. please suggest.

Thank you.

Upvotes: 2

Views: 60

Answers (1)

Samwise
Samwise

Reputation: 71424

If you only have one level of nested list to worry about, you can do this as a one-liner that normalizes the nested list to a 2D list of lists of ints, and then unpacks it in a nested generator:

>>> nums = [23,24,[10,11,12],56,85,[34,45,6]]
>>> min(n for i in nums for n in (i if isinstance(i, list) else [i]))
6

If you have arbitrary levels of nesting, use a recursive function:

>>> def nested_min(arr):
...     if isinstance(arr, int):
...         return arr
...     return min(nested_min(i) for i in arr)
...
>>> nested_min(nums)
6
>>> nested_min([10, 11, 12, [[1, 2], 3, 4], 5])
1

Upvotes: 5

Related Questions