Python嵌套列表, 将其中同位置的元素组成新的列表

2018-05-01  本文已影响0人  奥巴牛叔

#遍历:嵌套列表, 将其中同位置的元素组成新的列表

lsts = [[1,2,3], [4,5,6],[7,8,9],[10,11,12]]

方法一:

ret_x = [x for [x,y,z] in lsts]

ret_y = [y for [x,y,z] in lsts]

ret_z = [z for [x,y,z] in lsts]

print(ret_x)  #[1, 4, 7, 10]

print(ret_y)  #[2, 5, 8, 11]

print(ret_z)  #[3, 6, 9, 12]

打印结果:

[1, 4, 7, 10]

[2, 5, 8, 11]

[3, 6, 9, 12]

方法二:

ret_x=[x[0] for x in lsts]

ret_y=[x[1] for x in lsts]

ret_z=[x[2] for x in lsts]

print(ret_x)  #[1, 4, 7, 10]

print(ret_y)  #[2, 5, 8, 11]

print(ret_z)  #[3, 6, 9, 12]

打印结果同上:

[1, 4, 7, 10]

[2, 5, 8, 11]

[3, 6, 9, 12]

上一篇下一篇

猜你喜欢

热点阅读