简体   繁体   中英

List Comprehension with for Loops in Python

I have the following in python:

h = 0.05
p2 = [0,0]
p2[:] = [number - h for number in p2]

How would I define p2 using a regular for loop?

I initially thought that this would work:

for number in range(0,1,1):
    p2[number] = number - h

but that is not the case.

Here is a transliteration:

h = 0.05
p2 = [0,0]

_result = []
for number in p2:
     _result.append(number - h)

p2[:] = _result

del _result

So first the list comprehension creates a list. Then that list is used to mutate the original list, (using a whole-slice index-assignment on the list being referenced by p2 , this essentially just replaces the whole of the contents of p2 with the whole of the contents from the data on the right-hand side.

If you were going to use a regular for-loop, though, you'd probably just do:

h = 0.05
p2 = [0,0]

for i, number in enumerate(p2):
    p2[i] = number - h

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