如何正确迭代 Python 中的间隔?
How to properly iterate over intervals in Python?
我对Python很陌生(我更习惯C、C#)。我正在努力学习,我想尽可能 'Pythonic' 做事。
我想遍历区间,然后根据某个数字是否在区间内做一些事情。我知道我可以使用 numpy.arrange(或其他一些数组定义)创建我的间隔,然后像这样
遍历 bin
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 中被认为是 'bad form'。
我想做的更像这样
for ibin in ibins
if a is in ibin #somehow determine if a is in the bin
print('Hello')
有没有一种合理、快捷的方法来实现这一点?或者我的第一个建议是最好的方法。
我不想创建自定义间隔对象或类似的东西。
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')
如果您使用的是 Python 2,那么 xrange 方法优于 range.
这里有一个讨论: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!')
这会打印
(19, 21, 23, 25, 27)
(29, 31, 33, 35, 37)
(39, 41, 43, 45, 47)
(49, 51, 53, 55, 57)
found!
found!
我对Python很陌生(我更习惯C、C#)。我正在努力学习,我想尽可能 'Pythonic' 做事。
我想遍历区间,然后根据某个数字是否在区间内做一些事情。我知道我可以使用 numpy.arrange(或其他一些数组定义)创建我的间隔,然后像这样
遍历 binibins = 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 中被认为是 'bad form'。
我想做的更像这样
for ibin in ibins
if a is in ibin #somehow determine if a is in the bin
print('Hello')
有没有一种合理、快捷的方法来实现这一点?或者我的第一个建议是最好的方法。
我不想创建自定义间隔对象或类似的东西。
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')
如果您使用的是 Python 2,那么 xrange 方法优于 range.
这里有一个讨论: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!')
这会打印
(19, 21, 23, 25, 27)
(29, 31, 33, 35, 37)
(39, 41, 43, 45, 47)
(49, 51, 53, 55, 57)
found!
found!