簡體   English   中英

如何在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')

但是,閱讀各種文章后,據我了解,在Python中使用索引訪問bin元素被認為是“不良形式”。

我想做的是更多這樣的事情

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更好。

這里有一個討論: 對列表切片的迭代

這是最短的版本之一:

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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM