: for displaying all elements in a multidimensional array in python 3.1
I have a multidimensional array in python like:
arr = [['foo', 1], ['bar',2]]
Now, if I want to print out everything in the array, I could do:
print(arr[:][:])
开发者_运维问答
Or I could also just do print(arr). However, If I only wanted to print out the first element of each box (for arr, that would be 'foo', 'bar'), I would imagine I would do something like:
print(arr[:][0])
however, that just prints out the first data blog (['foo', 1]), also, I tried reversing it (just in case):
print(arr[0][:])
and I got the same thing. So, is there anyway that I can get it to print the first element in each tuple (other than:
for tuple in arr:
print(tuple[0])
)? Thanks.
You can transpose the array, e.g.
>>> list(zip(*arr))[0]
('foo', 'bar')
zip() will be a little slower than your original solution. If you don't like your original solution because it requires multiple lines of code you can always do this:
[i[0] for i in arr]
zip() has a for loop inside so you cannot be faster than a for loop using zip().
I think there might be a misunderstanding about how python parses the indexing. You can tack as many [:]
onto the array as you like and you'll get the same thing back.
>>> arr = [['foo', 1], ['bar',2]]
>>> print arr[:][:][:][:]
[['foo', 1], ['bar', 2]]
The second []
only indexes into the second dimension when you return an actual list-like object. It sounds like you want Matlab syntax like arr[:,0]
which you'll need to use something like numpy.
精彩评论