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
我尝试了[:: 1] [0],但它不起作用
I'm just start learning Python weeks ago. Python version = 2.7.9
我刚刚开始学习Python几周前。 Python版本= 2.7.9
4 个解决方案
#1
You can get the index [0]
from each element in a list comprehension
您可以从列表推导中的每个元素获取索引[0]
>>> [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
你也可以使用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
它将返回a中每个列表的第一个元素的列表
#4
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.
我代表a.So中的单个行,i [0]重新表示每行的第一个元素。
#1
You can get the index [0]
from each element in a list comprehension
您可以从列表推导中的每个元素获取索引[0]
>>> [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
你也可以使用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
它将返回a中每个列表的第一个元素的列表
#4
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.
我代表a.So中的单个行,i [0]重新表示每行的第一个元素。