这是一个二维列表,那么如何将横竖颠倒呢?
即变为:
1 4 7
2 5 8
3 6 9
>>> ls = [
[1,2,3],
[4,5,6],
[7,8,9]
]
>>> ls
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [y[i] for y in ls for i in range(3)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [[y[i]] for y in ls for i in range(3)]
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>> [[y[i] for y in ls] for i in range(3)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> for i in ls:
for j in range(len(i)):
print i[j]
print
1
2
3
4
5
6
7
8
9
>>> for i in ls:
for j in range(len(i)):
print i[j],
print
1 2 3
4 5 6
7 8 9
>>> for i in range(len(ls[0])):
for j in ls:
print j[i]
print
1
4
7
2
5
8
3
6
9
>>> for i in range(len(ls[0])):
for j in ls:
print j[i],
print
1 4 7
2 5 8
3 6 9
>>> zip(ls)
[([1, 2, 3],), ([4, 5, 6],), ([7, 8, 9],)]
>>> zip(*ls)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>
不知道大家看到没,for循环后面打一个","有出奇的作用
zip使用也一定要加 * ,这样就可以颠倒行与列。
来看看zip的使用:
>>> f_name=['A','B','C','E']
>>> l_name=['F','G','H','I']
>>> n_name=['J','K','L','M']
>>> zip(f_name,l_name)
[('A', 'F'), ('B', 'G'), ('C', 'H'), ('E', 'I')]
>>> zip(f_name,l_name,n_name)
[('A', 'F', 'J'), ('B', 'G', 'K'), ('C', 'H', 'L'), ('E', 'I', 'M')]
>>> zip(*zip(f_name,l_name,n_name))
[('A', 'B', 'C', 'E'), ('F', 'G', 'H', 'I'), ('J', 'K', 'L', 'M')]