[英]Looping an Python list while appending and iterating over fresh/new values
[英]Appending function values to a list while iterating
我是一個總 Python 新手所以請原諒我這個愚蠢的問題
composition()
function 返回某個值
但是我只希望值是<=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。而且我還想知道在 150 次composition()
中模擬的所有值我應該從什么樣的代碼開始?
我正在考慮將它與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()
提前致謝!
您可以創建一個生成器,該生成器將從composition()
生成n
值列表,並在其中n
<=
10 時停止。此列表將包括所有數字,因此您擁有所有中間值,以及此列表的長度將是生成它所需的“時間”。 例如(使用假隨機composition()
function:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.