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函数的python文档中:
示例:
如果需要结果是列表列表,而不是元组列表,则可以使用列表理解:
如果所有变量都存储在一个2d列表中,并且希望将其传递到zip函数中,则可以使用以下方法(我将其称为星号,因为我记不起它的正确英文术语):
http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html
zip
是正确的方法,如aga所示。但如果你想知道为什么你的原始代码不起作用:
这里有两个明显的问题,可能还有另外两个。(因为您没有向我们展示足够的代码或数据来确定,所以我无法保证这两个可能的代码或数据。)
可能
results
看起来像这样:当你做
for i in results
时,这意味着i
将是结果中的每个元素,也就是说,它将是[1, 2, 3]
,然后是[4, 5, 6]
。不能将列表用作列表的索引,因此这保证会给您一个TypeError: list indices must be integers, not list
。要解决此问题,您需要:
……或者
接下来,
results[j][i]
保证提高IndexError: list index out of range
,因为i
是每个行数,但您试图将其用作列数。如果在results
的行和列上迭代,则需要:接下来,除非用3个列表预先填充
rotated
,每个列表都预先填充了2个某种类型的对象,否则将得到IndexError: list assignment index out of range
。要解决此问题,需要预先填充
rotated
,如下所示:……或者
最后,我敢打赌
numCenturies
是3,在这种情况下,只要j
到达2
就可以得到另一个IndexError: list index out of range
。在这里,最简单的方法就是使用行的长度;这样就不可能出现一次性错误。总而言之:
但一般来说,Python提供了比预先创建数组和循环索引来填充值更简单的方法。您可以使用
append
-或者更好的是,使用列表理解。或者,更好的是,找到一种更高级的方法来编写您的使用,比如对zip
的单个调用。相关问题 更多 >
编程相关推荐