[英]Is there a way for finding the last list(not the last value) generated from Python iteration?
A = 300
Delta = 0.01
p0 = 100
ev0 = 0
dev = 0.001
dp0 = A*p0*dev
p = []
dp = []
ev = []
class Nonlinear():
def __init__(self):
self.p, self.dp, self.ev = p0, 0, ev0-dev
def __iter__(self):
return self
def __next__(self):
self.dp, self.p, self.ev = A*(self.p+self.dp)*dev, self.p + self.dp, self.ev+dev
p.append(self.p)
dp.append(self.dp)
if self.p > 1500:
raise StopIteration()
return p
for n in Nonlinear():
print(n)
The above are all the codes I use as an replacement of Excel in iteration.以上是我在迭代中用来代替Excel的所有代码。 The results always provide me with all the iterative lists rather than the last that I need.
结果总是为我提供所有迭代列表,而不是我需要的最后一个。 I wonder:
我想知道:
I use Python 3.8.我使用 Python 3.8。 If you have any ideas about solving the issue.
如果您对解决问题有任何想法。 Please let me know.
请告诉我。
I think this does what you want:我认为这可以满足您的需求:
class Nonlinear():
def __init__(self, p0 = 100, dp0 = 0, A = 300, dev = 0.001, maxval = 1500):
self.p = p0
self.dp = dp0
self.A = A
self.dev = dev
self.maxval = maxval
def __iter__(self):
while self.p + self.dp <= self.maxval:
self.p += self.dp
self.dp = self.A * (self.p + self.dp) * self.dev
yield self.p
n = Nonlinear()
print(*n)
# 100 130.0 178.0 245.8 339.88 470.068 650.1448 899.21128 1243.694608
Or或者
n = [_ for _ in Nonlinear()]
# [100, 130.0, 178.0, 245.8, 339.88, 470.068, 650.1448, 899.21128, 1243.694608]
You could also write as a generator:你也可以写成一个生成器:
def nonlinear(p = 100, dp = 0, A = 300, dev = 0.001, maxval = 1500):
Adev = A * dev
while(p + dp <= maxval):
p += dp
dp = Adev * (p + dp)
yield p
As a note, be careful how you define your variables.请注意,请注意如何定义变量。 Entering them line by line as I've done above gives different answers for
p
than having them listed in one line the way you have.像我上面所做的那样逐行输入它们给出了
p
的不同答案,而不是按照你的方式将它们列在一行中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.