【发布时间】:2013-01-29 15:55:49
【问题描述】:
我遇到了问题,我认为原因是由于插入函数的性质造成的。 文档说插入是这样工作的:
list.insert(index, object)
这里的重点是“对象”。为了执行适用于值的 if 语句,我将原始列表转换为数组。这个数组的数据类型是python自动计算出来的:
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)
更新/编辑:
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
是索引列表,其中 次要趋势类型 值存在(这些只是满足某些条件)。我想要实现的只是在每次出现 2 和 -2 值时插入标记 次要趋势类型 并在相应的站点重复索引值 小趋势 我试过使用 地图(i, x) 整数(次要趋势类型 [n]) 在循环和列表和列表理解中没有成功。我希望这能让事情更清楚。我不在乎它是如何完成的,只想实现它:)
【问题讨论】:
-
我在这之后遇到了很多困难。几个基本问题。 1.“为了执行适用于值的 if 语句,我将原始列表转换为数组。” - 这是为了使 if 语句更有效吗? Python 的 If 语句可以很好地处理任何类型的数据(包括数值)。如果这就是你所需要的,你就不需要 numpy. 2. 为什么要关心数据的数据类型? Python 旨在实现鸭子类型(即,您不关心类型,只关心功能)。
-
另外,我应该注意到,在 Python 中,所有的意图和目的都是一个“对象”。任何采用“对象”的函数都可以采用任何数据类型。
-
@Namey 感谢您的询问: 1) 我的意思是当我将列表转换为数组以便 if 语句识别数组中的任何值都是数字时(在这种情况下是整数)。当我使用列表执行 if 语句时,它不起作用。 2)我不关心数据类型,我只想让第二条语句起作用。我将在原始问题的编辑/更新中为您提供更多详细信息。希望这能更好地澄清事情。如果没有更新,干杯
标签: python list numpy insert type-conversion