简体   繁体   中英

How to iterate over (N-1) elements?

I want to iterate over N-1 elements in the for loop in python. For example, N=20, I want to start with the second element 2,3...20.

I have tried putting range(N-1), but it excludes the last element, not the first one.

for i in range(N):
    delta = (2 * np.random.rand(3) - 1) * max_delta
    trial[i] += delta

You can use:

for i in range(1, N):

The first parameter dictates which index to start from, with the second indicating the termination point.

Small note: The second element would have i = 1, not i = 2!

start should be 2, and end should n + 1 it should be range(2,n+1).

n = 20
start = 2 # first element in the loop (inclusive)
stop = n + 1 # stops before this number (exclusive)

# prints 2 to 20
for i in range(start, stop): 
    print(i)

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