简体   繁体   中英

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. The results always provide me with all the iterative lists rather than the last that I need. I wonder:

  1. If there is a way for finding the last list in Python 3.8.
  2. As the calculated results will be utilized to plot a figure using matplotlib, I want to get the relationship of p and ev calculated from iteration. Also it's also very important to swift the list into numpy array as well as gain the last iterative lists of p and ev including all evalues.

I use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM