Skip to main content
 首页 » 编程设计

python之分配给 for 循环值

2025年05月04日22sky-heaven

这真的是两个问题。

我有一个年龄区间列表。对于每个间隔,都有一个对应的值。间隔和值组织在元组列表中 age_value_intervals (查看代码中的注释)。

我还有一个单独的不同年龄列表,ages ,我想知道它的值(value)。

下面的代码试图将值映射到给定的年龄。

现在回答问题,

  1. 为了给value_map赋值我遍历了 ages和 value_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为此,连同 dict。当值无法映射到范围时,您可以手动考虑实例。

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.])