pythonic翻转列表/元组的方法 [英] pythonic way to flip a list/tuple

查看:55
本文介绍了pythonic翻转列表/元组的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

翻转"列表/元组的最Python方式是什么.

What is the most python way to "flip" a list/tuple.

flip我的意思是:如果a有元组的元组,可以与tuple [a] [b]之类的语法一起使用,则将其翻转",以便可以进行tuple [b] [a]到得到相同的物品.

What I mean by flip is: If a you have a tuple of tuples that you can use with syntax like tuple[a][b], "flip" it so that you can do tuple[b][a] to get the same item.

一个例子:

t = [
    [1, 2, 3]
    [4, 5, 6]
]

flipped(t) = [
    [1, 4]
    [2, 5]
    [3, 6]
]

推荐答案

它称为转置.

>>> t = [
...     [1, 2, 3],
...     [4, 5, 6]
... ]
>>> zip(*t)
[(1, 4), (2, 5), (3, 6)]
>>> map(list, zip(*t))
[[1, 4], [2, 5], [3, 6]]

如果 t 是NumPy array ,则它们具有属性 T 并返回转置:

If t were instead a NumPy array, they have a property T that returns the transpose:

>>> import numpy as np
>>> np.array(t)
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.array(t).T
array([[1, 4],
       [2, 5],
       [3, 6]])

这篇关于pythonic翻转列表/元组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆