简体   繁体   中英

Creating a list of N sublists

I'm working on a script that computes the sum of the elements of a list of lists of integers. I'm struggling with the input. I want the user to define the number of nested lists. The script is letting me input the desired number of lists and their contents but it only handles the last list and ignores the previous ones. I'm trying to use sp=[y] to get all the lists into sp , but it isn't working.

def nested_sum(sp):
    total = 0
    for nested in sp:
        total += sum(nested)
    return total

def main():
    n = int(input())
    for y in range(0,n):
         y = [int(x) for x in input().split()]
    sp=[y]
    print(sp)
    print(nested_sum(sp))

main()

You're close, but this part of your code isn't doing what you want:

    for y in range(0,n):
        y = [int(x) for x in input().split()]
    sp=[y]
  • The first line above iterates over a range of integers, setting y to each of those integers in turn.

  • The second line runs each "turn" through the loop , replacing the y you just set with the result of the list comprehension [int(x) for x in input().split()] .

  • The third line runs after the loop is finished, and puts the final y value by itself into a list called sp .

So, you're changing the value of y twice every time through the loop, but each time you replace that value, the previous value is lost, and sp ends up as a list containing only the final value of y .

What you need to do is save each of those values in another list. You can do that with the list.append() method:

def main():
    n = int(input())
    sp = []  # create an empty list 'sp'
    for i in range(0,n):  # use a separate loop counter variable 'i'
        y = [int(x) for x in input().split()]
        sp.append(y)  # append y to the end of sp
    print(sp)
    print(nested_sum(sp))

As you can see, the sp list is set up before the loop starts, and each value of y is appended to the end of it inside the loop.

In this case, you don't actually need to use different i and y variables, but it's a good idea to avoid reusing variable names to do different things in the same function – and especially, not to replace loop counters inside a loop (which is an easy way to confuse yourself and introduce errors).

Your nested_sum() function (and the main() call at the end) can stay the same.

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