简体   繁体   中英

How to slice multi dimensional list in python under certain condition?

I want to slice a multidimensional list under certain condition. I have a sensor which gives a pair of (quality, angle, distance) as a multidimensional list. ex. a = [(10,0,3),(10,10,6),(10,15,4),(10,20,5),(10,3,3),(10,5,6)]

now if the distance is greater than 5 from that point I need to detect the angle also. Now within the 10-degree+ angle, I need to slice the array, doesn't matter what the distance is.

so my result would be:

b= [(10,10,6),(10,15,4),(10,20,5)]

as the distance is 6 and the angle range is between 10 to 10+10=20.

I will be so glad if you could give me an idea how to find the index of that particular list which fulfills the condition, so that i can sliec the list.

You could write a function ( take ) like this:

a = [(10, 0, 3), (10, 10, 6), (10, 15, 4), (10, 20, 5), (10, 3, 3), (10, 5, 6)]


def take(lst, th=5):
    idx = next(i for i, e in enumerate(lst) if e[2] > th)  # get the index of the first with distance > th
    quality, angle, distance = lst[idx]  # unpack in quality, angle, distance

    return [e for e in lst[idx:] if angle <= e[1] <= angle + 10]  # filter the list starting from idx


result = take(a)

print(result)

Output

[(10, 10, 6), (10, 15, 4), (10, 20, 5)]

If using Pandas is an option, here is a way to do it:

i = 5
j = 10

df = pd.DataFrame(a, columns = ('quality', 'angle', 'distance'))
print(df)

     quality  angle  distance
0       10      0         3
1       10     10         6
2       10     15         4
3       10     20         5
4       10      3         3
5       10      5         6

Here ix1 is the index of the first occurrence of the first condition on the distance , and ix2 the index of the last succeeding rows that fullfil the condition imposed on angle :

ix1 = df[df['distance'] > i].iloc[0].name
ix2 = (~(df.loc[ix1:, 'angle'] >= j)).idxmax()-1
l = df.loc[ix1:ix2,:]

list(l.to_records(index=False))
[(10, 10, 6), (10, 15, 4), (10, 20, 5)]

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