Apply Indicator Function to List
10,228
Solution 1
bysign = [int(x >= 0) for x in somelist]
Solution 2
Just use a list comprehension:
>>> orig = [-3, 2, 5, -6, 8, -2]
>>> indic = [1 if x>0 else 0 for x in orig]
>>> indic
[0, 1, 1, 0, 1, 0]
Solution 3
To produce the results of your example, I probably would have done
cmp_list=map(cmp, your_list)
one_zero_list=[]
for item in cmp_list:
if item < 0:
one_zero_list.append(0)
elif item==0:
one_zero_list.append(0) #you didnt actually say what to do with 0
else:
one_zero_list.append(1)
Author by
cdelsola
Updated on June 14, 2022Comments
-
cdelsola almost 2 years
Is there an easy way to apply an indicator function to a list? i.e. I have a list with some numbers in it and I would like to return another list of the same size with, for example, ones where the positive numbers were in the original list and zeros where the negative numbers were in the original list.