gpt4 book ai didi

Python 列表理解 : set all elements in an array to 0 or 1

转载 作者:太空狗 更新时间:2023-10-30 00:29:53 25 4
gpt4 key购买 nike

我一直在尝试想出一个单行列表理解来执行以下操作:给定一个整数数组和一个整数,将其称为 int1,我想创建一个仅包含 0 和 1 的新数组,这样如果原始数组中的那个位置有一个 int1,则新数组的值为 1,否则为 0。

有没有办法像在 C 中一样让 True/False 为 1/0?

array1 = [1,4,2,4,5,6,4,3]
array2 = [x == 4 for x in array1 ]
=> [False, True, False, True, False, False, True, False]

最佳答案

简单地将 bool 值转换为int,使用int函数,像这样

array2 = [int(x == 4) for x in array1]

输出

[0, 1, 0, 1, 0, 0, 1, 0]

之所以可行,是因为在 Python 中,Boolean is a subclass of int .

关于Python 列表理解 : set all elements in an array to 0 or 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21949539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com