Cod*_*ner 26 python list python-2.x multidimensional-array
我有一个这样的列表:
a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))
Run Code Online (Sandbox Code Playgroud)
我想要一个像这样的结果(列表中的每个第一个元素):
4.0, 3.0, 3.5
Run Code Online (Sandbox Code Playgroud)
我尝试了[:: 1] [0],但它不起作用
我刚刚开始学习Python几周前.Python版本= 2.7.9
Cor*_*mer 50
您可以[0]
从列表推导中的每个元素获取索引
>>> [i[0] for i in a]
[4.0, 3.0, 3.5]
Run Code Online (Sandbox Code Playgroud)
也正好是迂腐,你没有list
的list
,你有一个tuple
的tuple
.
Jor*_*ley 26
使用拉链
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
Run Code Online (Sandbox Code Playgroud)
你也可以使用numpy
a = numpy.array(a)
print a[:,0]
Run Code Online (Sandbox Code Playgroud)
小智 10
你可以用这个:
a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))
a = np.array(a)
a[:,0]
returns >>> array([4. , 3. , 3.5])
Run Code Online (Sandbox Code Playgroud)
3种方法比较
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)
Run Code Online (Sandbox Code Playgroud)
Zip 方法效果最好。当我必须为未安装 numpy 的集群服务器中的 mapreduce 作业执行一些列明智的过程时,它非常有用。