【问题标题】:Appending function values to a list while iterating迭代时将函数值附加到列表
【发布时间】:2020-07-26 18:09:28
【问题描述】:

我是一个 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()

提前致谢!

【问题讨论】:

    标签: python list numpy append


    【解决方案1】:

    您可以创建一个生成器,该生成器将从composition() 生成值列表n,并在n 其中&lt;= 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
    

    【讨论】:

      猜你喜欢
      • 2014-09-06
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      相关资源
      最近更新 更多