“错误:设置具有序列的数组元素" [英] "Error: setting an array element with a sequence"
问题描述
我正在尝试将Matlab代码转换为Python,但是在数组中添加零时却收到错误消息.
I am trying to convert Matlab code into Python, but I'm receiving an error when I append zeros in my array.
Matlab代码:
N_bits=1e5;
a1=[0,1];
bits=a1(ceil(length(a1)*rand(1,N_bits)));
bits=[0 0 0 0 0 0 0 0 bits];
Python 代码:
a1=array([0,0,1])
N_bits=1e2
a2=arange(0,2,1)
## Transmitter ##
bits1=ceil(len(a2)*rand(N_bits))
bits=a1[array(bits1,dtype=int)]
bits=array([0,0,0,0,0,0,0,0, bits])
我在最后一行出现错误:
I get an error on the last line:
Error:
bits=array([0,0,0,0,0,0,0,0, bits])
ValueError: setting an array element with a sequence.
推荐答案
您想将列表与数组连接,所以请尝试
You want to join the list with the array, so try
bits=concatenate(([0,0,0,0,0,0,0,0], bits))
其中 concatenate()
是 numpy.concatenate()
.您还可以使用 zeros(8,dtype = int)
代替零列表(请参阅
where concatenate()
is numpy.concatenate()
. You can also use zeros(8, dtype=int)
in place of the list of zeros (see numpy.zeros()
).
与Matlab不同,Python中的 [0,0,0,0,0,0,0,0,bit,类似,它会创建一个列表,该列表的开头为零,后跟一个嵌入列表.
Unlike in Matlab, something like [0,0,0,0,0,0,0,0, bits]
in Python creates a list with the initial zeros follows by an embedded list.
Matlab:
>> x = [1,2,3]
x =
1 2 3
>> [0,0,x]
ans =
0 0 1 2 3
Python:
>>> x = [1,2,3]
>>>
>>> [0,0,x]
[0, 0, [1, 2, 3]]
>>>
>>> [0,0] + x
[0, 0, 1, 2, 3]
这篇关于“错误:设置具有序列的数组元素"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!