문제

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.

도움이 되었습니까?

해결책 2

List comprehensions!

bysign = [int(x >= 0) for x in somelist]

Here's a demo.

다른 팁

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]

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top