Reputation: 496
Let's say I have a list with ages(that represent the life expectancy a country):
ages= ['70.37668898', '72.15779044', '73.25278702', '72.18979793', '80.73137673','55.43124818' '54.16265064', '54.16540964', ...]
Now I have ranges of life expectancy that go up by two(range 48-100), something like this:
48-50,50-52, ...., 98-100
I would like to create a new list that has a list for every age in ages. The inner list contains a 1 if the given age is inside a life expectancy range and a 0 if it's not.
So the result would look something like this:
Each inner list belongs to an age from ages
[[0,0,0,0,1, ..., 0],[0,1,0,0,0, ..., 0],...]
How can I accomplish this?
Upvotes: 1
Views: 4212
Reputation: 6035
Your structure for ranges is a bit vague. Lets assume your ranges are something like these
ranges = [(48,50),(50,52),...(98,100)]
Now
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]
Or if your ranges are fixed, starting from 50 to 100 with increment by two, you can use 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]
Upvotes: 5
Reputation: 10172
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]
results in
[[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]]
which is (maybe) what you asked.
Upvotes: 1