: for displaying all elements in a multidimensional array in python 3.1
Solution 1
You can transpose the array, e.g.
>>> list(zip(*arr))[0]
('foo', 'bar')
Solution 2
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().
Leif Andersen
Updated on June 05, 2022Comments
-
Leif Andersen almost 2 years
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.