简体   繁体   English

创建一个由5x5随机数组成的面板

[英]Create a panel of 5x5 random numbers

The assignment says that I have to create a panel of random numbers 5x5 and calculate the sum of the numbers per line, per pile and calculate the sum of numbers of the diagonal of the panel. 作业说,我必须创建一个随机数为5x5的面板,并计算每条线,每堆数字的总和,并计算面板对角线的数字之和。 The results must be saved in a text file. 结果必须保存在文本文件中。 It would be very helpfull if you solve this with the command "for". 如果使用命令“ for”解决此问题,将非常有帮助。

For example like this code: 例如如下代码:

import random

randnumb = []   
for i in range(10):   
    line= []
    for j in range(4):
        line.append(random.randint(1,1000))    
    randnumb.append(line)    
a=open("a.txt","w")  
for i in range(10):    
    g=""   
    for j in range(4):    
        g += str(randnumb[i][j])+ " " 
    g += "\n"  
    a.write(g)   
a.close()    
a=open("a.txt","r")    
print(a.read())    
a.close()

I used for but you can replace it for a map , if you want. 我曾经用过for但是如果需要,可以将其替换为map

import random

# generates 5 x 5 random matrix
random.seed(23)
a = [[random.random() for _ in range(5)] for x in range(5)]

rowSums = [sum(row) for row in a] # for each row ... sum the numbers in the list...
columnSums = [sum(col) for col in zip(*a)] # for each column ... sum the numbers in the list...
diagonalSum = sum([a[i][i] for i in range(len(a))])

# print results
print rowSums
# [3.4414822773841207, 1.720709091012754, 1.4966213860156654, 2.084642254225464, 3.621865231749428]

print columnSum
# [2.7740025507928237, 3.035484154123261, 2.4396250416690193, 1.3413097355704942, 2.774898758231834]

print diagonalSum
# 2.8094518166

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

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