[英]Appending function values to a list while iterating
I am a total Python newbie so pardon me for this stupid question我是一个总 Python 新手所以请原谅我这个愚蠢的问题
The composition()
function returns a certain value composition()
function 返回某个值
However I only want the value to be <=10
, and I want 100 of them The code below calculates the times it took to simulate 100 composition()
values to be of <=10
但是我只希望值是
<=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))
However, Suppose that the code above returns 150. And I also want to know all the values that were being simulated in 150 times of composition()
What kind of code should I start with?但是,假设上面的代码返回 150。而且我还想知道在 150 次
composition()
中模拟的所有值我应该从什么样的代码开始?
I am thinking about combining it with the if else method statement
and appending the values to an empty list, but so far my code has been a total disaster我正在考虑将它与
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()
Thanks in advance!提前致谢!
You could make a generator that will generate n
of list of values from composition()
and stop when n
of them are <=
10. This list will include all the numbers, so you have all the intermediate values, and the length of this list will be how "long" it took to generate it.您可以创建一个生成器,该生成器将从
composition()
生成n
值列表,并在其中n
<=
10 时停止。此列表将包括所有数字,因此您拥有所有中间值,以及此列表的长度将是生成它所需的“时间”。 For example (with a fake random composition()
function:例如(使用假随机
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.