LVmiao
LVmiao

Reputation: 1

How to move a boolean value from one array to another in python

I am recently solving a coding problem. It ask me to move all 0s in one array to the end of the array. Like [0, 1, 1, 0, 0, 1]->[1, 1, 1, 0, 0, 0].

The reality is there could be any type of data in the original array, for example, [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]

what I am doing is looping the array, compare if it is 0, if it is, put it into another array. If it is not, increase the counter, at the end put the same amount of 0s as the counter. However, it treats the Boolean Value False as 0, so I can't do this, I am just curious if there is a way that can separate False from 0, and put into another array as False in Python. Thanks.

Upvotes: 0

Views: 338

Answers (3)

I run into some issues with 0.0 so, i made some changes

array = [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]
filt = lambda x: True if x==0 and type(x) is not bool else False
print(sorted(array,key=filt))

The x==0 will allow you to filter the float, and type(x) in not bool will help you with the boolean False

Upvotes: 0

syntaxError
syntaxError

Reputation: 866

Use the test in your algorithm, to check if the value is the integer 0 and not the bool.

test = lambda x: True if x is 0 else False

list_ = [0, "A", 1 , None, False, True, 0, 0, 20, 1, 0.0]

print(sorted(list_, key=test)) #['A', 1, None, False, True, 20, 1, 0.0, 0, 0, 0]

Upvotes: 1

idjaw
idjaw

Reputation: 26600

You can make use of is which does an identity comparison. Observe the following example:

>>> n = 0
>>> n is 0
True
>>> n is False
False
>>> False is n
False

Upvotes: 0

Related Questions