Python How to get every first element in 2 Dimensional List

落花浮王杯 提交于 2020-01-09 13:14:24

问题


I have a list like this :

a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))

I want an outcome like this (EVERY first element in the list) :

4.0, 3.0, 3.5

I tried a[::1][0], but it doesn't work

I'm just start learning Python weeks ago. Python version = 2.7.9


回答1:


You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a]
[4.0, 3.0, 3.5]

Also just to be pedantic, you don't have a list of list, you have a tuple of tuple.




回答2:


use zip

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

you can also use numpy

a = numpy.array(a)
print a[:,0]



回答3:


You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a




回答4:


Compared the 3 methods

  1. 2D list: 5.323603868484497 seconds
  2. Numpy library : 0.3201274871826172 seconds
  3. Zip (Thanks to Joran Beasley) : 0.12395167350769043 seconds
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
    for j in range(10):
        b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1

array=np.array(D2_list)
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=array[:,j]        
Numpy_time=time.time()-t1

D2_trans = list(zip(*D2_list)) 
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=D2_trans[j]
Zip_time=time.time()-t1

print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)

The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.




回答5:


Try using

for i in a :
  print(i[0])

i represents individual row in a.So,i[0] represnts the 1st element of each row.



来源:https://stackoverflow.com/questions/30062429/python-how-to-get-every-first-element-in-2-dimensional-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!