如何优化这样的代码?

时间:2017-06-15 09:01:33

标签: python arrays if-statement optimization range

我们有一个360度的风向,有一定的步骤,如何优化这个代码?

if 348.75 <= data['wind_deg'] <= 360 or 0 < data['wind_deg'] < 11.25:
    print("wind: N")

if 11.25 <= data['wind_deg'] <= 33.75:
    print("wind: N-N-E")

if 33.75 <= data['wind_deg'] <= 56.25:
    print("wind: N-E")

if 56.25 <= data['wind_deg'] <= 78.75:
    print("wind: E-N-E")

if 78.75 <= data['wind_deg'] <= 101.25:
    print("wind: E")

if 101.25 <= data['wind_deg'] <= 123.75:
    print("wind: E-S-E")

if 123.75 <= data['wind_deg'] <= 146.25:
    print("wind: S-E")

if 146.25 <= data['wind_deg'] <= 168.75:
    print("wind: S-S-E")

if 168.75 <= data['wind_deg'] <= 191.25:
    print("wind: S")

if 191.25 <= data['wind_deg'] <= 213.75:
    print("wind: S-S-W")

if 213.75 <= data['wind_deg'] <= 236.25:
    print("wind: S-W")

if 236.25 <= data['wind_deg'] <= 258.75:
    print("wind: W-S-W")

if 258.75 <= data['wind_deg'] <= 281.25:
    print("wind: W")

if 281.25 <= data['wind_deg'] <= 303.75:
    print("wind: W-N-W")

if 303.75 <= data['wind_deg'] <= 326.25:
    print("wind: N-W")

if 326.25 <= data['wind_deg'] <= 348.75:
    print("wind: N-N-W")

我想我需要使用类似的东西:

wind = ['N','NE','ENE','E','ESE','S-E','S','SSW','SW','W','WNW ”, 'NW', '西北偏北']

参考学位,但我不知道怎么做正确

1 个答案:

答案 0 :(得分:0)

this is an option:

wind = ['N', 'NNE','NE','ENE','E','ESE','SE', 'SSE',
        'S', 'SSW', 'SW','WSW', 'W','WNW','NW','NNW']
delta_phi = 22.5

# this is where the directions are centered
degs = [delta_phi*d for d in range(0, len(wind))]

def get_dir(d):
    d += delta_phi/2
    d %= 360
    index = int(d/delta_phi)
    return wind[index]

or more compact:

def get_dir(d):
    index = int(((d+delta_phi/2) % 360)/delta_phi)
    return wind[index]

not thoroughly tested; just made this test run:

for i in range(361):
    print(i, get_dir(i))