简体   繁体   中英

Updating a list in a loop in python without using the append function.

Hi there suppose I have;

a = np.array([1.,2.])
b = np.array([3.,4.])
r = []
... 
for i in range(10)
    b*i
    r[i] = ((a[0]+b[0]) - (a[1] - b[1]))
    ...
i = i+1

The code is meant to take arrays a and b and perform addition and subtraction on elements from them, and place them into what I think should be a list, which in this case I've called r. (ie so r[0] = 0, r[1] = 6 etc.)

I know this does not work, but I don't know why can someone tell me what I should define 'r' to be?

I'd rather avoid using something like;

r.append(...) 

The end goal is to plot r vs i , should I therefore construct both lists and then plot them against eachother, or should I include it in the loop somehow.

Thanks in advance!

Use list comprehensions, as an example, I'm going to rewrite your whole for loop and r = [] into this:

r = [((a[0]+(b*i)[0]) - (a[1] - (b*i)[1])) for i in range(1,10)]

This does the same, more readable, much more faster.

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