如何在python中反转2d列表 [英] How to I invert a 2d list in python

查看:75
本文介绍了如何在python中反转2d列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维列表,如下所示:

I have a 2d list like this:

   1   2   3

   4   5   6

我想做这个:

   1   4

   2   5

   3   6

我试图做一个for循环并切换每个值,但是我一直使索引超出界限错误.这是我所拥有的:

I've tried to do a for loop and switch each value but I keep getting an index out of bound error. Here's what I have:

for i in results:
    for j in range(numCenturies):
        rotated[i][j] = results [j][i]

推荐答案

来自

此函数返回一个元组列表,其中第i个元组包含每个参数序列或可迭代对象中的第i个元素.返回的列表的长度被截断为最短参数序列的长度.当有多个长度都相同的参数时,zip()类似于map(),其初始参数为None.使用单个序列参数,它将返回一个1元组的列表.没有参数,它将返回一个空列表.

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

示例:

zip([1, 2, 3], [4, 5, 6]) # returns [(1, 4), (2, 5), (3, 6)]

如果需要将结果作为列表列表而不是元组列表,则可以使用列表推导:

If you need the result to be the list of lists, not the list of tuples, you can use list comprehension:

[list(x) for x  in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])] # returns [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

如果所有变量都存储在一个2d列表中,并且希望将其传递到zip函数中,则可以使用以下代码(我将其命名为星形符号,因为我可以记得正确的英语用语):

If all your variables are stored in one 2d list, and you want it pass it into zip function, you can use the following (I'll call it the star notation, because I can't remember the proper English term for it):

results = [[1, 2, 3], [4, 5, 6]]
zip(*results) # returns [(1, 4), (2, 5), (3, 6)]

这篇关于如何在python中反转2d列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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