如何使用python从1d数组创建带有3个元素的2d数组

时间:2015-03-31 08:44:35

标签: python

signals=([1998  ,1968  ,1937  ,1827  ,2027,2286  ,2484  ,2266  ,2107  ,1690,1808  ,1927  ,1924  ,1959  ,1889,1819  ,1824  ,1979  ,1919  ,1845,1801  ,1799  ,1952  ,1956  ,1969,2044  ,2100  ,2103  ,2110  ,2375,
    2030  ,1744  ,1699  ,1591  ,1770,1950  ,2149  ,2200  ,2294  ,2146,2241  ,2369  ,2251  ,2126  ,2000,1759  ,1947  ,2135  ,2319  ,2352,2476  ,2296  ,2400  ,3126  ,2304,
    2190  ,2121  ,2032  ,2161  ,2289,2137  ,2130  ,2154  ,1831  ,1899,2117  ,2266  ,2176  ,2089  ,1817,2162  ,2267])

Vectors=[[signals[i-1],signals[i+1],signals[i+3]] for i in range(1,len(signals-4))]
print Vectors

TypeError                                 Traceback (most recent call last)
<ipython-input-2-6f5b7430197d> in <module>()
     16     2190  ,2121  ,2032  ,2161  ,2289,2137  ,2130  ,2154  ,1831  ,1899,2117  ,2266  ,2176  ,2089  ,1817,2162  ,2267])
     17 
---> 18 Vectors=[[signals[i-1],signals[i+1],signals[i+3]] for i in range(1,len(signals-4))]
     19 print Vectors
     20 

TypeError: unsupported operand type(s) for -: 'list' and 'int'


Expected Output:[[signals[0],signals[2], signals[4]],[signals[1],signals[3],signals[5]],[signals[2],signals[4],signals[6]]] 

2 个答案:

答案 0 :(得分:1)

您的管道未正确放置:len(signals-4)应为len(signals) - 4

答案 1 :(得分:1)

错误在range函数中,您需要括号signals,因为您要从signals列表的长度中减去4:

range(1,len(signals)-4))