Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

python - Summation of values in nested lists

I have encountered a problem where a return gives None back, though the variable had a value just a single line of code before.

mylist = [[7]]

def sumcalc(the_list,n):
    s = n
    for x,y in enumerate(the_list):
        if type(y) == list:
            sumcalc(y,s)
        elif type(y) == int:
            s += y
            if x < len(the_list)-1:
                sumcalc(the_list[x+1], s)
            else:
                print (s)
                return s
    
print(sumcalc(mylist,0))

The print command in the second to last line gives me 7, as expected. But the return is None. Any help on this would be appreciated :)

question from:https://stackoverflow.com/questions/65862035/summation-of-values-in-nested-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sumcalc() doesn't do anything on its own; you need to use the return value. Beyond this, the index checking is unecessary, as the return could simply be placed after the loop. Here is a simpler way of writing the nested sum code.

def nested_sum(x):
    if type(x)==int:
        return x
    if type(x)==list:
        return sum(
            nested_sum(item)
            for item in x
        )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...