问题
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
- 2D list: 5.323603868484497 seconds
- Numpy library : 0.3201274871826172 seconds
- 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