这是我到目前为止所做的:
import random
list1 = []
list2 = []
for i in range(5):
for j in range(3):
list1.append(random.randrange(1,101))
list2.append(list1)
list1=[]
for i in list2:
for j in i:
print(j, end=",")
print(" (Sum: ", sum(i), " Average: ", (sum(i)/len(i)), ")", sep="")
print()
我希望能够在每列上找到最大和最小的数字。例如,输出将是:
1,91,46, (Sum: 138 Average: 46.0)
82,62,21, (Sum: 165 Average: 55.0)
39,52,41, (Sum: 132 Average: 44.0)
60,69,45, (Sum: 174 Average: 58.0)
20,21,7, (Sum: 48 Average: 16.0)
Largest number of first column: 82 Smallest number of first column: 1
Largest number of second column: 91 Smallest number of second column: 21
Largest number of third column: 46 Smallest number of third column: 7
我知道min / max,有什么方法可以用它来获得这些结果吗?或者我必须使用不同的方法?任何帮助表示赞赏!
答案 0 :(得分:1)
您可以使用zip(*rows)
rows = [[randrange(1, 101) for col in range(5)] for row in range(3)]
for column in zip(*rows):
print(
column,
'sum:', sum(column),
'avg:', int(sum(column) / len(column)),
'min:', min(column),
'max:', max(column),
)
示例输出:
(5, 22, 95) sum: 122 avg: 40 min: 5 max: 95
(92, 88, 67) sum: 247 avg: 82 min: 67 max: 92
(97, 61, 3) sum: 161 avg: 53 min: 3 max: 97
(95, 37, 67) sum: 199 avg: 66 min: 37 max: 95
(47, 13, 29) sum: 89 avg: 29 min: 13 max: 47
如果您使用的是numpy,则可以使用ndarray
而不是嵌套列表。使用array.T
(转置)迭代列而不是行。
for column in numpy.array(rows).T:
print(column, column.sum(), column.mean(dtype=int), column.min(), column.max())
[ 5 22 95] 122 40 5 95
[92 88 67] 247 82 67 92
[97 61 3] 161 53 3 97
[95 37 67] 199 66 37 95
[47 13 29] 89 29 13 47