Skip to main content
 首页 » 编程设计

python之使用 NumPy 。关于数字或替代数组的 binary_repr之Python

2025年05月04日9lhb25

我尝试使用以下代码将数字列表转换为二进制数,但出现错误

import numpy as np 
 
lis=np.array([1,2,3,4,5,6,7,8,9]) 
a=np.binary_repr(lis,width=32) 

程序运行后报错是

Traceback (most recent call last):

File "", line 4, in a=np.binary_repr(lis,width=32)

File "C:\Users.......", in binary_repr if num == 0:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有什么办法可以解决这个问题?

请您参考如下方法:

您可以使用 np.vectorize来克服这个问题。

>>> lis=np.array([1,2,3,4,5,6,7,8,9]) 
>>> a=np.binary_repr(lis,width=32) 
>>> binary_repr_vec = np.vectorize(np.binary_repr) 
>>> binary_repr_vec(lis, width=32) 
array(['00000000000000000000000000000001', 
       '00000000000000000000000000000010', 
       '00000000000000000000000000000011', 
       '00000000000000000000000000000100', 
       '00000000000000000000000000000101', 
       '00000000000000000000000000000110', 
       '00000000000000000000000000000111', 
       '00000000000000000000000000001000', 
       '00000000000000000000000000001001'], dtype='<U32')