按升序添加随机生成的值

adding randomly generated values in increasing order

我想在 if else statement.How 中添加随机生成的值,而不是固定的 0.20.5 值,有人可以指导我吗?提前致谢。

我的密码是

N=10
dta=[]
x=0.0
for i in range(N):
    dta.append(x)

    if(i<5):
        x=x+0.2  #here instead of 0.2 randomly generated data in range 0.1 to 0.2
                 #should be added( example it may be 0.15,0.16....)
    else:
        x=x+0.5  #here instead of 0.5 randomly generated data in range 0.3 to 0.5
                 #should be added
print(dta)  

应该这样做:

import random
N=10
dta=[]
x=0.0
for i in range(N):
    dta.append(x)

    if(i<5):
        x += random.uniform(0.1, 0.2)
    else:
        x += random.uniform(0.3, 0.5)
print(dta)

示例输出:

[0.0, 0.13515152101736566, 0.2866133692895604, 0.4608222800319004, 0.6003500994767033, 0.7898596366391699, 1.2677308143972574, 1.571917695358207, 1.8899333979603337, 2.2967764098732637]

更新:

要使值本身在 0.1, 0.20.3, 0.5 范围内并按递增顺序排列,如 OP 的评论所示,您可以这样做:

import random
N=10
dta = sorted([random.uniform(*(0.1, 0.2) if i < 5 else (0.3, 0.5)) for i in range(N)])
print(dta)

示例输出:

[0.10928830948278306, 0.13885822930882388, 0.15861800478212257, 0.16539989224271684, 0.18145832131929895, 0.34643148884688224, 0.3570560993108919, 0.44518489503000336, 0.48017733976314136, 0.4992591196660774]

如果您更喜欢 easier-to-read 方法,这会做同样的事情:

import random
N=10
dta=[]
for i in range(N):
    if(i<5):
        x = random.uniform(0.1, 0.2)
    else:
        x = random.uniform(0.3, 0.5)
    dta.append(x)
dta.sort()
print(dta)