迭代时将函数值附加到列表中

时间:2020-04-14 04:01:22

标签: python list numpy append

我是Python新手 所以请原谅我这个愚蠢的问题

composition()函数返回某个值

但是我只希望值是<=10,我希望其中的100个 下面的代码计算将100个composition()值模拟为<=10

所花费的时间
def find():
    i=1
    aaa=composition()
    while(aaa>10):
        aaa=composition()
        i=i+1        
    return i

Customers_num=[find() for i in range(100)]
Customers_num=np.array(Customers_num)
print(np.sum(Customers_num))

但是,假设上面的代码返回150。 我还想知道在composition()的150倍中模拟的所有值 我应该以哪种代码开头?

我正在考虑将其与if else method statement结合起来并将这些值附加到一个空列表中,但是到目前为止,我的代码已经完全灾难了

def find():
    i=1
    aaa=composition()
    bbb=[]
    if aaa<=10:
        bbb.appendd([aaa])
    else:
        bbb.append([aaa])
        aaa=composition()
        bbb.appendd([aaa])
        while(aaa>10):
            i=i+1
            if aaa>10:
                bbb.append([aaa])
            else:
                bbb.append([aaa])            
    return i,bbb

find()

提前谢谢!

1 个答案:

答案 0 :(得分:-1)

您可以使生成器从n生成composition()的值列表,并在其中n<= 10时停止。此列表将包括所有数字,因此您具有所有中间值,并且此列表的长度将是生成该列表所需的时间。例如(使用伪随机composition()函数:

from random import randint

def composition():
    return randint(0, 20)


def getN(n):
    while n > 0:
        c = composition()
        if c < 10:
            n -= 1
        yield c

values = list(getN(10)) # get 10 values less than 10
# [2, 0, 11, 15, 12, 8, 16, 16, 2, 8, 10, 3, 14, 2, 9, 18, 6, 11, 1]

time = len(values)
# 19
相关问题