1

假设我有一个年龄列表(代表一个国家的预期寿命):

ages= ['70.37668898', '72.15779044', '73.25278702', '72.18979793', '80.73137673','55.43124818' '54.16265064', '54.16540964', ...]

现在我的预期寿命范围增加了两倍(范围 48-100),如下所示:

48-50,50-52, ...., 98-100

我想创建一个新列表,其中包含每个年龄段的列表。如果给定的年龄在预期寿命范围内,则内部列表包含 1,否则为 0。

所以结果看起来像这样:

每个内部列表都属于年龄范围内的一个年龄

[[0,0,0,0,1, ..., 0],[0,1,0,0,0, ..., 0],...] 

我怎样才能做到这一点?

4

2 回答 2

5

您的范围结构有点模糊。让我们假设你的范围是这样的

ranges = [(48,50),(50,52),...(98,100)]

现在

ages= ['70.37668898', '72.15779044', '73.25278702', '72.18979793', '80.73137673','55.43124818' '54.16265064', '54.16540964', ...]

result = [ [ 1 if (r[0] <= age <= r[1]) else 0 for r in ranges] for age in ages]

或者,如果您的范围是固定的,从 50 到 100 以 2 为增量,您可以使用生成器:

result = [ [ 1 if (r[0] <= age <= r[1]) else 0 for r in ( (i-2,i) for i in range(50,100,2)) ] for age in ages]
于 2013-01-22T22:30:50.430 回答
1
ages = [70.37668898, 72.15779044, 73.25278702, 72.18979793, 80.73137673, 55.43124818, 54.16265064, 54.16540964]
[[int(age >= 48+2*i and age <50+2*i) for i in range(25)] for age in ages]

结果是

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

这(也许)是你问的。

于 2013-01-22T22:29:22.483 回答