假设我有一个有年龄的列表(代表一个国家的预期寿命):
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],...]
我该如何做到这一点?
答案 0 :(得分: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,您可以使用generator:
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]
答案 1 :(得分: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]]
这是(也许)你提出的问题。