Skip to main content
 首页 » 编程设计

Python 列表插入函数和数据类型问题

2025年05月04日13jackei

我有一个问题,我认为原因是插入函数的性质。 文档说插入是这样工作的:

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 

是一个整数列表,如下所示: 次要趋势类型 = [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 值时插入标记 次要趋势类型 并在相应站点重复索引值 小趋势 我试过使用 map (我,X) int(次要趋势类型[n]) 在一个循环中列出并列出理解但没有成功。我希望这能让事情变得更清楚。我不关心它是如何完成的,只想实现它:)

请您参考如下方法:

哈利路亚!解决方案在于 MinorTrendArr2.dtype = '对象' 而不是 'int64' 正如我怀疑的那样。解决方案在于以下循环:

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]]) 

这应该是:

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]]) 

唯一的区别是插入到列表中的对象周围有 [ ]。然后python假定数组 次要趋势Arr2 成为 'int64' 而不是对象,并允许正确计算下一个 if 语句:)

干杯