Home>

There are about 100 double lists with a length of 12 per list.
alist = [[1,2,3,4,5,6,7,8,9,10,11,12], [], [], .... [... 8,9,10,11 , 12]]
It is a double list like.
I don't know how to add the numbers in the same position like these 1s and 2s.
As for what I want to do, I have data for 12 months of temperature for 100 years, and I want to find the average monthly temperature for 100 years.
For the time being
for x in range (12):
for y in range (100)
I tried it like this, but I didn't understand.

  • Answer # 1

    Maybe you should use numpy. I'll give you a simple example.

    import numpy as np
    lst1 = [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
    a = np.array (lst1)
    lst2 = list (a.sum (axis = 0))
    print (lst2)
    # [10, 14, 18]


    For details, refer to Calculate total, average, maximum, minimum, etc. for each row/column of NumPy array.

  • Answer # 2

    This is an example of calculating with a list. For the sake of simplicity, the data is for two years (the average temperature in Japan in 1990 and 1991).

    alist = [[5.0,7.8,10.6,14.7,19.2,23.5,25.7,28.6,24.8,19.2,15.1,10.0],
             [6.3,6.5,9.5,15.4,18.8,23.6,26.7,25.5,23.9,18.1,13.0,9.2]]
    result = [0] * 12
    for i in alist:
        for j in range (len (i)):
            result [j] + = i [j]
    num = len (alist)
    for i in range (num):
        result [i] = result [i]/num
    print (result)
    # [5.65, 7.15, 20.1, 30.1, 38.0, 47.1, 52.4, 54.1, 48.7, 37.3, 28.1, 19.2]

  • Answer # 3

    If you want to add up the monthly temperature data, prepare an empty array for "12 months".

    Then, the outside of the double loop is set to "year" and the inside is set to "month", and it is rotated by "range".
    In the inner loop, specify "month" for the array to be summed, and add the data of the double list.

    I will post an example of the total program, so please try it.

    month = [0] * 12
    for x in range (100):
        for y in range (12):
            month [y] + = alist [x] [y]
    print (month)

  • Answer # 4

    Here is an example using the built-in function zip.

    for z in zip (* alist):


    If you write, the contents of each list in alist(1, 10, 1), (2, 20, 3), (3, 30, 5), (...)You can take them out in order like this.
    The rest is thisstatistics.meanYou can find the average value by combining such items.

    from statistics import mean
    alist = [[1, 2, 3, 4, 5, 6],
             [10, 20, 30, 40, 50, 60],
             [1, 3, 5, 7, 9, 11]]
    avg = []
    for z in zip (* alist):
        print (z)
        avg.append (mean (z))
    print (avg)
    # When writing in one line in comprehension
    # avg2 = [mean (z) for z in zip (* alist)]