Python 中将布尔值列表转换为整数列表
将布尔值列表转换为整数列表:
- 使用列表理解来遍历列表。
- 使用
int()
类将每个布尔值转换为整数。 - 新列表将只包含整数。
import numpy as np
# ✅ 将布尔值列表转换为整数列表
list_of_booleans = [True, False, False, True]
list_of_integers = [int(item) for item in list_of_booleans]
print(list_of_integers) # 👉️ [1, 0, 0, 1]
# -----------------------------------------------------
# ✅ 将布尔数组转换为整数数组
arr = np.array([True, False, False, True], dtype=bool)
int_arr = arr.astype(int)
print(int_arr) # 👉️ [1 0 0 1]
我们使用列表推导将布尔值列表转换为整数列表。
列表推导用于对每个元素执行一些操作,或者选择满足条件的元素子集。
在每次迭代中,我们将当前布尔值传递给 int()
类以将其转换为整数。
list_of_booleans = [True, False, False, True]
list_of_integers = [int(item) for item in list_of_booleans]
print(list_of_integers) # 👉️ [1, 0, 0, 1]
int
类返回一个由提供的数字或字符串参数构造的整数对象。
如果没有给出参数,构造函数返回 0。
新列表包含原始列表中布尔值的整数表示。
或者,我们可以使用 map()
函数。
使用 map() 将布尔列表转换为整数列表
将布尔值列表转换为整数列表:
- 将
int()
类和列表传递给map()
函数。 map()
函数将使用列表中的每个布尔值调用int()
类。- 使用
list()
类将地图对象转换为列表。
list_of_booleans = [True, False, False, True]
list_of_integers = list(map(int, list_of_booleans))
print(list_of_integers) # 👉️ [1, 0, 0, 1]
map()
函数将一个函数和一个可迭代对象作为参数,并使用可迭代对象的每个项目调用该函数。
int()
类传递列表中的每个布尔值并将每个值转换为整数。
最后,我们使用 list()
类将 map 对象转换为列表。
列表类接受一个可迭代对象并返回一个列表对象。
使用 numpy 将布尔数组转换为整数数组
使用 astype()
方法将布尔数组转换为整数数组,例如 int_arr = arr.astype(int)
。 astype()
方法将返回包含值的整数表示的数组副本。
import numpy as np
arr = np.array([True, False, False, True], dtype=bool)
int_arr = arr.astype(int)
print(int_arr) # 👉️ [1 0 0 1]
我们可以在 numpy
数组上使用 astype
方法来复制数组并将其转换为指定的类型。
我们传递给 astype
方法的唯一参数是数组转换为的数据类型。
要将布尔数组转换为整数数组,请将 int
类传递给 astype()
方法。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。