简体   繁体   中英

Python Loop While Until Condition Is Met

I am trying to create a while or if loop to step through sequentially a list to return the number of steps needed until the value changes. Here is a sample of my list. For the first items (through the 47), the loop would put out 1. For the first 39, the loop would put out 3, for the second 39 it would put out 2, for the third it would put out 1. Then for the first 31 it would put 5, then for the next 31 it would put 4, etc.

I am not exactly sure how to do this and if it can be done using a while loop. I think it might be able to be done with an iterator/counter that starts at 1, and then steps up (+= 1) until the value changes. I think it would be a 'while list[orig index] == list[orig + iterator index], iterate the counter and test whether equal. That said, I don't know how while loops could again assess the original true condition with the new 'iterator' value.

list1 = [[81, 79, 74, 57, 47, 39, 39, 39, 31, 31, 31, 31, 31, 30, 27, 22, 20,

You can use a numpy array to iterate the conditions. For example:

#Array to check
x = np.array([81, 79, 74, 57, 47, 39, 39, 39, 31, 31, 31, 31, 31, 30, 27, 22, 20])
#Counts
y = np.ones(x.shape)

#Loop for each gap, check for equality, and add to y
for i in range(1, x.shape[0]):
    y[:-i] = np.where(x[:-i]==x[i:], y[:-i]+1, y[:-i])
print(y)

which should yield:

>>> [1. 1. 1. 1. 1. 3. 2. 1. 5. 4. 3. 2. 1. 1. 1. 1. 1.]

There are many other ways to do this so you can explore other options too.

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