質問

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