python如何区分bool和int

问题描述 投票:0回答:5

我有一个阵列。它包含不同类型的值。例如,

[1,2,3,'a', False,0,5,0,3] 

任务是将所有零移动到数组的末尾。事实上,它应该是这样的

[1,2,3,'a',False,5,3,0,0]

我的问题是如何区分布尔值False0?我正在尝试逐一分析这些值与0进行比较。

但是,Python没有看到0和False之间有任何区别,最后我有类似下面的内容

[1,2,3,'a', 5,3, 0, 0, 0]
python boolean
5个回答
4
投票

在Python中,由于历史性和不破坏兼容性的原因,bool是“int”的子类,False和true只是求值为0和1。

您可以使用自定义键函数,除了等于零之外,还检查元素的类型。然后,因为你最后只需要0,所以使用bool的“0和1”等价 - 函数中布尔表达式失败的元素被评估为“0”并放在所有其余元素之前。

mylist.sort(key=lambda value: value == 0 and not isinstance(value, bool))

保证密钥为“False”的其余元素的订单保留:qazxsw poi(感谢Patrick Haugh)


1
投票

您可以从零中过滤列表,并添加一个列表,其中包含已在过滤列表末尾找到的零数:

https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

输出:

s = [1,2,3,'a', False,0,5,0,3]
new_s = [i for i in s if isinstance(i, int) and i or isinstance(i, bool)]+[0]*s.count(0) 

1
投票

Python有一个内置函数type(),它返回参数的“type”对象。

你可以简单地做:

[1, 2, 3, False, 5, 3, 0, 0, 0]

1
投票

对于这个问题,类型检查是个好主意。您可以检查当前元素是否为array = [1,2,3,'a', False,0,5,0,3] #Initial Array for element in range(len(array)): #Iterating indexes in the array if type(array[element])==type(1) and array[element] == 0: #If the type of the element is an Integer AND If element is equal to 0 e = array.pop(element) #Remove the element from its current position array.append(e) #Adding the element at the end of the array element -= 1 #Decrementing current index print(array) ,而不是0类型,并删除该元素并将其添加到列表的末尾:

bool

哪个输出你想要的:

lst = [1,2,3,'a', False,0,5,0,3] 

for i, x in enumerate(lst):
    if x == 0 and not isinstance(x, bool):
        lst.append(lst.pop(i))

print(lst)

或者你可以制作两个列表,一个用零,一个用非零,然后将它们加在一起。对于非零列表,元素不能是[1, 2, 3, 'a', False, 5, 3, 0, 0] ,但可以是0类型,因为bool不会移动到最后。但是,对于零列表,元素必须是False,而不是0类型,因为我们不想将bool移动到最后。

以下是一些示例:

1.使用列表推导

False

2.使用non_zeroes = [x for x in lst if x != 0 or isinstance(x, bool)] zeroes = [x for x in lst if x == 0 and not isinstance(x, bool)] print(non_zeroes + zeroes) # [1, 2, 3, 'a', False, 5, 3, 0, 0]

filter()

注意:对于类型检查,我们可以在这里使用non_zeroes = list(filter(lambda x: x != 0 or isinstance(x, bool), lst)) zeroes = list(filter(lambda x: x == 0 and not isinstance(x, bool), lst)) print(non_zeroes + zeroes) # [1, 2, 3, 'a', False, 5, 3, 0, 0] type()。你可以选择其中之一。


0
投票

你可以在一个循环中做这样的事情:

首先收集一个列表中非零的所有int值,并在第二个列表中全部为零,最后扩展列表:

isinstance()

输出:

list_1=[1,2,3,'a', False,0,5,0,3]

all_zero=[]
all_int=[]
for i in list_1:
    if i!=0:
        all_int.append(i)
    else:
        all_zero.append(i)

all_int.extend(all_zero)
print(all_int)
© www.soinside.com 2019 - 2024. All rights reserved.