簡體   English   中英

分配給循環值

[英]Assigning to for-loop values

這確實是兩個問題。

我有年齡間隔清單。 對於每個間隔,都有一個對應的值。 時間間隔和值在元組age_value_intervals列表中進行組織(請參見代碼中的注釋)。

我也有一個單獨的清單,列出了不同的年齡段, ages ,我想知道這些值。

下面的代碼嘗試將值映射到給定的年齡。

現在到問題,

  1. 為了分配一個值value_map我遍歷兩個agesvalue_map使用zip 然后我試圖給value 這行不通。 為什么?

  2. 我懷疑我使用的方法是否有效(如果可行)。 有沒有更好的方法來實現此映射?


import numpy as np

# List of tuples defining and age interval and the corresponing value for
# that interval. For instance (20, 30, 10) indicates that the age interval from
# 20 to 30 has the value 10
age_value_intervals = [(20, 30, 10),
                       (30, 35, 5),
                       (35, 42, 50),
                       (50, 56, 40),
                       (56, 60, 30)]

# The ages for which I would like to know the value
ages = [25, 30, 35, 40, 45, 50]

# Empty array used to stor the values for the corresponding age
value_map = np.empty(len(ages))
# I want the value to be nan if there is no known value
value_map[:] = np.nan

# Iterate over the ages I want to know the value for
for age, value in zip(ages, value_map):
    # Check if the age is in an interval for which the value is known
    for from_age, to_age, actual_value in age_value_intervals:
        if age >= from_age and age < to_age:
            # Assign the value to the value_map
            # This is were it falls apart (I guess...)
            value = actual_value
            # Move on to the next age since we got a match
            break

#Expected output
value_map = [10, 5, 50, 50, nan, 40]

我建議您numpy.digitize使用numpy.digitizedict 當值無法映射到范圍時,您可以手動考慮實例。

import numpy as np

age_value_intervals = [(20, 30, 10),
                       (30, 35, 5),
                       (35, 42, 50),
                       (50, 56, 40),
                       (56, 60, 30)]

ages = np.array([25, 30, 35, 40, 45, 50])

bins = np.array([x[0] for x in age_value_intervals])
mapper = dict(enumerate([x[2] for x in age_value_intervals], 1))    

res = np.array([mapper[x] for x in np.digitize(ages, bins)], dtype=float)

for idx in range(len(ages)):
    if not any(i <= ages[idx] <= j for i, j, k in age_value_intervals):
        res[idx] = np.nan

結果:

array([ 10.,   5.,  50.,  50.,  nan,  40.])

首先,如注釋中所述,如果您嘗試分配給當前在循環內更改的變量,則該值會丟失。

其次,大多數映射是多余的。

這樣的事情可能仍然可以改善,但應該可以:

result=[] 
for check_age in ages:
    for from_age, to_age, value in age_value_intervals:
        if check_age in range(from_age, to_age):
            result+=[value]

print result

請注意,如果您還需要在年齡不在間隔內時添加一些結果,則需要附加代碼。

暫無
暫無

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

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