Confused with arrays in python
Is this the correct way to declare and iterate through an array in Python, where each element is multiplied by a constant value?
timeArr开发者_开发百科ay = array([0]*1000)
for x in timeArray:
timeArray[x] = x * deltaTime
print(timeArray)
timeArray = [i*deltaTime for i in range(1000)]
will construct a list with the contents that you want. Indexing into a list takes O(1) time, the same as for an array. Python lists are very fast, they're actually implemented as arrays.
Are you sure you want to print
the contents of the array/list while it's being constructed?
(Aside: If you want faster arrays because you're doing number crunching, then a Numpy array might be a better choice:
timeArray = numpy.arange(1000)
timeArray *= deltaTime
)
This is probably less confusing, and does what you want.
timeArray = [0 for i in range(1000)]
for x in timeArray:
timeArray[x] *= deltaTime
print(timeArray)
It looks like what you really need are numpy arrays. The built-in array behaves more like lists.
#!/usr/bin/python
from array import array
timeArray = array("f", [1]*1000)
deltaTime = 2
for i, x in enumerate(timeArray):
timeArray[i] = timeArray[i] * deltaTime
print(timeArray)
# but numpy arrays behave more "naturally".
from numpy import array
timeArray = array([1]*1000, dtype="f")
print (timeArray * 2)
A numpy array will multiply all elements of the array by a scalar value. Besides, I'm not sure that your original array code actually works. Also, numpy arrays are much faster.
精彩评论