在一定条件下如何在python中切片多维列表?

2024-04-19 23:47:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在一定条件下,我想切片一个多维列表。我有一个传感器,它提供了一个多维列表(质量,角度,距离)对。 ex. a = [(10,0,3),(10,10,6),(10,15,4),(10,20,5),(10,3,3),(10,5,6)]

如果距离这个点大于5,我也需要检测角度。现在在10度+角范围内,我需要对数组进行切片,不管距离是多少。你知道吗

所以我的结果是:

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

因为距离是6,角度范围是10到10+10=20。你知道吗

如果你能告诉我如何找到满足条件的那张单子的索引,我会很高兴的,这样我就可以浏览这张单子了。你知道吗


Tags: 距离列表质量切片传感器数组条件ex
2条回答

您可以这样编写函数(take):

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)

输出

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

如果使用Pandas是一个选项,下面是一种方法:

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

这里ix1是第一个条件在distance上第一次出现的索引,而ix2是最后一个连续行的索引,该行满足施加在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)]

相关问题 更多 >