生成4列数据,使每行总和为100

时间:2014-09-01 16:42:32

标签: python

如何编写一个可以随机生成4列数据的python程序,使每行的数字总和为100?

2 个答案:

答案 0 :(得分:2)

>>> import numpy as np
>>> A = np.random.rand(10,4)
>>> A /= A.sum(axis=1)[:,np.newaxis]
>>> A *= 100
>>> A

array([[ 52.65020485,   8.39068184,   4.89730114,  34.06181217],
       [ 58.32667159,   8.99338257,  13.7326809 ,  18.94726494],
       [  8.23847677,  36.27990343,  14.73440883,  40.74721097],
       [ 37.10408209,   5.31467062,  39.47977538,  18.10147191],
       [ 21.5697797 ,  14.80630725,  12.69891923,  50.92499382],
       [ 15.46006657,  24.62499701,  37.37736874,  22.53756768],
       [  6.66777748,  25.62326117,  11.80042839,  55.90853296],
       [ 38.81602256,  26.74457165,   3.4365655 ,  31.00284028],
       [  5.67431732,   7.57571558,  44.01330459,  42.73666251],
       [ 33.09837171,  26.66421892,  10.90188895,  29.33552043]])

这会根据您的要求生成正实数。它们在均匀分布中是随机的。如果您想要不同的发行版,可以在np.random中找到其他几个选项。

答案 1 :(得分:0)

import random
def Column(n):
    integers = []
    for i in range(n):
        A = random.randrange(0,100)
        B = random.randrange(0,100-A)
        C = random.randrange(0,100-(A+B))
        D = (100 - (A+B+C))
        integers.append((A,B,C,D))
    return integers

Returns = Column(4)
for i in Returns:
    print(i)
    print(i[0]+i[1]+i[2]+i[3])

对不起,如果它很乱,就得走了。