gpt4 book ai didi

Python - 基于范围的子列表选择的补充

转载 作者:行者123 更新时间:2023-11-28 22:53:36 25 4
gpt4 key购买 nike

我想知道是否有 python“核心”语法来处理基于范围的选择的补充。

说说

 a = [0,1,2,3,4,5,6]

然后,例如,

 offset = 1
step = 3
a[offset::step] = [1,4].

因此我的问题是:

“我可以这样吗

 a[~(offset::step)] == [0,2,3,5,6]

不使用 ifs?"

或者,“处理这个问题的最 pythonic 方法是什么?”

附录:

假设我必须对数千个可变大小(即可变时间长度的轨迹)列表(实际上是粒子轨迹)进行子采样操作。所以我无法预先计算出正确的索引集。

最佳答案

集(通常)快一个数量级,即使您不提前填充索引也是如此:

r100 = range(100)
r2 = range(3, 40, 3)

# Find indices in r100 that aren't in r2.
# This is a set difference (or symmetric difference)
## Set methods
# Precalculated is fastest:
sr100 = set(r100)
sr2 = set(r2)
%timeit sr100 - sr2
100000 loops, best of 3: 3.84 us per loop

# Non-precalculated is still faster:
%timeit set(range(100)) ^ set(range(3,40,3))
100000 loops, best of 3: 9.76 us per loop
%timeit set(xrange(100)) ^ set(xrange(3,40,3))
100000 loops, best of 3: 8.84 us per loop

# Precalculating the original indices still helps, if you can hold it in memory:
%timeit sr100 ^ set(xrange(3,40,3))
100000 loops, best of 3: 4.87 us per loop

# This is true even including converting back to list, and sorting (if necessary):
%timeit [x for x in sr100 ^ set(xrange(3,40,3))]
100000 loops, best of 3: 9.02 us per loop
%timeit sorted(x for x in sr100 ^ set(xrange(3,40,3)))
100000 loops, best of 3: 15 us per loop


## List comprehension:

# Precalculated indices
%timeit [x for x in r100 if x not in r2]
10000 loops, best of 3: 30.5 us per loop

# Non-precalculated indices, using xrange
%timeit [x for x in xrange(100) if x not in xrange(3, 40, 3)]
10000 loops, best of 3: 65.8 us per loop

# The cost appears to be in the second xrange?
%timeit [x for x in r100 if x not in xrange(3, 40, 3)]
10000 loops, best of 3: 64.3 us per loop
%timeit [x for x in xrange(100) if x not in r2]
10000 loops, best of 3: 29.9 us per loop
# xrange is not really any faster than range here - uses less memory, but still have
# to walk through entire list
%timeit [x for x in range(100) if x not in range(3, 40, 3)]
10000 loops, best of 3: 63.5 us per loop

关于Python - 基于范围的子列表选择的补充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19243427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com