[英]: for displaying all elements in a multidimensional array in python 3.1
I have a multidimensional array in python like: 我在python中有一个多维数组,例如:
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). 或者我也可以只打印(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:
但是,如果我只想打印出每个框的第一个元素(对于arr,则为'foo','bar'),我会想像这样:
print(arr[:][0]) 打印(ARR [:] [0])
however, that just prints out the first data blog (['foo', 1]), also, I tried reversing it (just in case): 但是,这只是打印出第一个数据博客(['foo',1]),而且,我尝试将其反转(以防万一):
print(arr[0][:]) 打印(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, eg 您可以转置数组,例如
>>> list(zip(*arr))[0]
('foo', 'bar')
zip() will be a little slower than your original solution. zip()会比您原来的解决方案慢一些。 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(). zip()内部有一个for循环,因此您不能比使用zip()的for循环更快。
I think there might be a misunderstanding about how python parses the indexing. 我认为关于python如何解析索引可能存在误解。 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. 听起来您想要使用
arr[:,0]
类的Matlab语法,您将需要使用numpy之类的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.