简体   繁体   English

如何在python中添加和显示随机生成的列表列表的垂直元素?

[英]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]? 现在的问题是:如何添加所有列表的垂直对应元素,并在所有列表顶部的新列表中将总和显示为[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. 如果要对这些列表进行其他操作,则可能要将它们存储在某种数据结构中,可能使用Numpy将它们放在矩阵中。

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. 做最简单的方法只是这是有某种变量,说col_sums = [0,0,0]你的循环之前进行初始化),并因为它的产生增加每个随机列表的值。 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. zip()接受旧的总和和随机值,并为您提供一个元组,该元组包含每个粘贴在一起的列表的N个值。 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)] . 例如,在第一次迭代中,您将具有col_sums = [0,0,0]zip(col_sums, my_randoms)将给您[(0,1), (0,1), (0,2)] map ping sum across that list gives you a new list like [1, 1, 2] . 该列表map ping sum为您提供了一个新列表,例如[1, 1, 2] If you put this in every iteration, you'll have a nice sum built up at the end. 如果将其放在每个迭代中,最后都会得到一个不错的总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM