简体   繁体   中英

How to add and display vertical elements of randomly generated list of lists in python?

The following simple code will generate a list of lists of three elements and the total of the elements in each list on the same line.

import random
for i in xrange(3):
    my_randoms1 = [random.randrange(1,6,1) for _ in range (3)]
    print my_randoms1,"\t", sum(my_randoms1)

Now the question is: How could I add the vertical corresponding elements of all lists and display the sums in a new list on top of all lists as [T1,T2,T3]? Thanks

[T1,T2,T3]

[1, 1, 2]   4
[5, 3, 4]   12
[5, 1, 5]   11

If you're going to be doing anything else with these lists, you probably want to store them in some sort of data structure, possibly using Numpy to place them in a matrix.

The simplest way to do just this is to have some sort of variable, say col_sums = [0,0,0] (initialized before your loop) and add the values of each random list as it's generated. You can do this with nested loops but if you want to get fancy, you can use something like:

col_sums = map(sum, zip(col_sums, my_randoms))

zip() takes your old sums and your random values and gives you a tuple holding the N th value of each list stuck together. For example, the first iteration, you'd have col_sums = [0,0,0] and zip(col_sums, my_randoms) would give you [(0,1), (0,1), (0,2)] . map ping sum across that list gives you a new list like [1, 1, 2] . If you put this in every iteration, you'll have a nice sum built up at the end.

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