分配给forloop值

2024-04-20 13:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这其实是两个问题。你知道吗

我有一份年龄间隔表。每个间隔都有一个对应的值。间隔和值被组织在一个元组列表age_value_intervals(参见代码中的注释)。你知道吗

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

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

现在来回答问题

  1. 为了给value_map赋值,我使用zipagesvalue_map进行迭代。然后我尝试分配给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]

Tags: andthetofrommapforage间隔
2条回答

首先,如注释中所述,如果您试图将当前正在循环中更改的变量赋值,那么该值就会丢失。你知道吗

其次,大多数映射是冗余的。你知道吗

像这样的事情可能仍然可以改进,但应该会奏效:

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

注意,如果您还需要在间隔中的年龄而不是时添加一些结果,则需要附加代码。你知道吗

我建议您将^{}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.])

相关问题 更多 >