简体   繁体   中英

Can't get the walrus operator to work (Python double list comprehension)

This list comprehension does not work:

buy_prices = [(buylow := round(0.997 + ii/10000.0, 5), max(jj, buylow)) for jj in [buylow, 0.9982] for ii in range(21)]

NameError: name 'buylow' is not defined

This one doesn't either:

buy_prices = [(buylow, max(jj, buylow)) for jj in [buylow := round(0.997 + ii/10000.0, 5), 0.9982] for ii in range(21)]

SyntaxError: assignment expression cannot be used in a comprehension iterable expression

How am I supposed to do this? Or do I just have to do the round calculation for buylow twice?

I'd highly recommend not using nested list comprehensions, since that is not very readable to many people.

Instead maybe something like this:

buy_prices = list()
for ii in range(21):
    buylow = round(.997 + ii / 10000, 5)
    for jj in (buylow, .9982):
        buy_prices.append((buylow, max(jj, buylow))

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