如何在Python中正确地迭代间隔?

2024-10-01 09:21:24 发布

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

我对Python相当陌生(我更习惯于C,C#)。我正在努力学习,我想尽可能地做一些“Python式”的事情。在

我想在区间上迭代,然后根据一个数是否在区间内做一些事情。我知道我可以用numpy.排列(或其他一些数组定义)然后像这样在容器上迭代

ibins = numpy.arange(start = 19, stop = 67, step = 2)
a = 50
for idx, val in enumerate(ibins) :
    if idx > 0:
        if ibins[idx - 1] <= a < ibins[idx] : 
            #do something more meaningfull
            print('Hello')

然而,阅读各种帖子,我的理解是使用索引访问bin元素在Python中被认为是“糟糕的形式”。在

我想做的是更像这样的事情

^{pr2}$

有没有一个合理、快捷的方法来实现这一点?或者我的第一个建议是最好的方法。在

我不想创建自定义间隔对象或类似的对象。在


Tags: 对象方法numpyif定义数组事情start
2条回答

这里有一个讨论:Iteration over list slices

这是最短的版本之一:

import numpy as np

lst = np.arange(start = 19, stop = 67, step = 2)
bin_width = 5
search = 50

for ibin in zip(*(iter(lst),) * bin_width):
    print(ibin)
    if min(ibin) <= search <= max(ibin):
        print('found!')
    # or this? not sure what you want...
    if ibin[0] <= search <= ibin[-1]:
        print('found!')

这个指纹

^{pr2}$
start = 19
stop = 67
step = 2

for bin in [range(i, i+step) for i in range(start, stop, step)]:
    if a in bin:
        print('Hello')

如果您使用的是python2,那么xrange方法比range要好。在

相关问题 更多 >