简体   繁体   中英

is there a way to check for the first match element when comparing two arrays without using loops in Python?

I have this grid array which contains numbers from 0 to 7. A slot can be considered free on the grid only if it is a 0 and there's no different number before it:

[0, 0, 0, 0, 1, 0, 0, 0]           # every 0 before the 1 is a free slot

I want to make it so that the program can find the first slot that contains a number from 1 to 7, so that it knows that all the previous slots are free. I can make it work using a loop, like:

array = [0, 0, 0, 0, 1, 0, 0, 0]
freeslot = len(array)-1               # initializing in case it does not find a match
for n in range(1, 8):
   if (n in array) and (array.index(n)-1 < freeslot):
         freeslot = array.index(n)-1

The thing is, whenever I'm running this to check the grid, I check for 15 different arrays, so I feel that a loop makes it too slow. Is there a way to make it not using loops, or at least make it more efficient?

一个可能的解决方案是使用一个 numpy 数组并看看这个解决方案: Numpy 第一次出现的值大于现有值

This should work. freeslot = list(map(lambda x: True if 7 >= x > 0 else False, array)).index(True) . Basically what it does is replace everything in a array list copy that is less than 7 but over 1 and replaces it with True. Then it indexes the first case of True in the new copy.

ans = len(arr) - 1

for i, v in enumerate(arr):
    if v > 0:
        ans = i - 1
        break

ans
# 3

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