这其实是两个问题。你知道吗
我有一份年龄间隔表。每个间隔都有一个对应的值。间隔和值被组织在一个元组列表age_value_intervals
(参见代码中的注释)。你知道吗
我还有一个不同年龄的单独列表ages
,我想知道它的值。你知道吗
下面的代码试图将值映射到给定的年龄。你知道吗
现在来回答问题
为了给value_map
赋值,我使用zip
对ages
和value_map
进行迭代。然后我尝试分配给value
。这不管用。为什么?
我怀疑我使用的方法是否有效(如果它有效的话)。有没有更好的方法来实现这种映射?
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]
首先,如注释中所述,如果您试图将当前正在循环中更改的变量赋值,那么该值就会丢失。你知道吗
其次,大多数映射是冗余的。你知道吗
像这样的事情可能仍然可以改进,但应该会奏效:
注意,如果您还需要在间隔中的年龄而不是时添加一些结果,则需要附加代码。你知道吗
我建议您将^{} 与
dict
一起使用。当值无法映射到范围时,可以手动计算实例。你知道吗结果:
相关问题 更多 >
编程相关推荐