我有一个问题,我相信原因是由于插入函数的性质。 文档说插入的工作原理是这样:在这里Python列表插入函数和数据类型问题
list.insert(index, object)
的关键点是“对象”。为了执行一个对值起作用的if语句,我将原始列表转换为一个数组。该数据类型此数组的已自动通过蟒计算为如下:
In [25]: MinorTrendTypeArr.dtype
Out[25]: dtype('int64')
然而在列表
MinorTrendType
的新的数组插入所需的项目之后,
MinorTrendTypeArr2
如前所述,这必须是因为插入函数的方法将对象项添加到列表中。 具有数据类型
In [25]: MinorTrendTypeArr2.dtype
Out[25]: dtype('object')
这是通过尝试将所述
MinorTrendType
变量转换到新的阵列时,接收以下错误进一步证实。
In [27]: run triptrade.py
This is the length of MinorTrendType the first time = 12356
This is the length of MinorTrendType after adding plustwos elements = 13179
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
173 else:
174 filename = fname
--> 175 __builtin__.execfile(filename, *where)
/home/kane/tripkane_python/triptrade.py in <module>()
579
580 MinorTrendArr2 = np.array(MinorTrend, dtype = np.int64)
--> 581 MinorTrendTypeArr2 = np.array(MinorTrendType, dtype = np.int64)
582
583
ValueError: setting an array element with a sequence.
但是同样的问题在没有输入外部值的变量中不会出现。我认为可能有更好的方式来做事,但我现在使用的知识非常有限。任何帮助,替代方案的建议将是最受欢迎的。注意:由于输入项目会改变列表的长度,所以我无法在一个循环中输入所有必需的值,除非上述提到的解决方法更简单。
由于提前,
凯恩
for n in range(0, len(MinorTrendType)):
if MinorTrendTypeArr[n] == 2:
plustwos.append(n)
pl = []
mi = []
PS1 = len(MinorTrendType)
print "This is the length of MinorTrendType the first time = %d" %PS1
for n in range(0, len(plustwos)):
bbgun = plustwos[n] + len(plustwos[0:n])
pl.append(bbgun)
MinorTrendType.insert(pl[n], 22)
MinorTrend.insert(pl[n], MinorTrend[pl[n]])
PS2 = len(MinorTrendType)
print "This is the length of MinorTrendType after adding plustwos elements = %d" %PS2
MinorTrendArr2 = np.array(MinorTrend, dtype = np.int64)
MinorTrendTypeArr2 = np.array(MinorTrendType, dtype = np.int64)
UPDATE /编辑:
MinorTrendType
是像这样整数列表: MinorTrendType = [1,0,-1, 1,0,-1,2,-1,1,-1,0,0,0,2,1,0,0,-1,2,1,0,-2 ........ ....]
MinorTrend
是一个索引列表,其中存在 MinorTrendType (这些值仅仅满足某些条件)。所有我想要实现的是内 MinorTrendType 插入在2每次出现时标记和-2值和内 在correpsonding网站复制的指数值MinorTrend 我一直在使用 图(I,X) INT试图(MinorTrendType [ n]) 内循环和列表和列表解析没有成功。我希望这使事情更清晰。我不在乎它是如何完成的,只是想实现它:)
我有以下这个颇有几分难度。几个基本问题。 1.“为了执行一个能够处理值的if语句,我将原始列表转换为一个数组。” - 这是为了让if语句更有效率吗? Python的If语句很好地处理任何类型的数据(包括数值)。如果这就是你需要的一切,你不需要numpy。 2.为什么你关心数据的数据类型? Python的目的是鸭子型(即,你不关心类型,只是功能)。 – Namey 2013-02-14 02:01:38
另外,我应该注意到,在Python中,所有的意图和目的都是“对象”。任何接受'对象'的函数都可以使用任何数据类型。 – Namey 2013-02-14 02:03:22
@Namey感谢您的查询:1)我的意思是,当我将列表转换为数组,以便if语句识别数组中的任何值是数字(在本例中为整数)时。当我用列表进行if语句时,它不起作用。 2)我不会给老鼠一些数据类型,我只是想让第二条语句正常工作。我会在原始问题的编辑/更新中提供更多细节。希望这可以让事情更好一点。如果它没有更新,干杯 – tripkane 2013-02-14 03:14:03