我想要翻转二维列表上的行和列,但遇到了麻烦。 Python 不允许将值分配给未初始化的“单元格”。我不知道如何初始化我的网格,因为我不知道提前的长度。以下内容:
data = list()
maReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='"')
for rindex, row in enumerate(maReader):
for iindex, item in enumerate(row):
data[iindex][rindex] = item
失败并出现“IndexError:列表分配索引超出范围”错误。我可以循环两次,第一次计算列和行,然后初始化网格,然后再次循环并赋值,但这似乎非常浪费。
我对 Python 还很陌生,并且认为有一种我缺少的简单方法可以做到这一点。
感谢您的帮助。
I am looking to flip the rows and columns on a 2D list and am running into trouble. Python won't allow a value to be assigned to an uninitialized 'cell'. I am not sure how to initialize my grid since I don't know the length ahead of time. The following:
data = list()
maReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='"')
for rindex, row in enumerate(maReader):
for iindex, item in enumerate(row):
data[iindex][rindex] = item
fails with a "IndexError: list assignment index out of range" error. I could loop through twice, the first time to count columns and rows, than initialize the grid, than loop again and assign values, but that seems awfully wasteful.
I am pretty new to Python and figure there is a simple way to do this that I am missing.
Thanks for the help.
发布评论
评论(4)
这是与 @retracile 的 LBYL 方法。
Here's an EAFP counterpoint to @retracile's LBYL approach.
假设所有行的长度相等,您可以这样处理:
Assuming all rows of equal length, you can approach it like this:
这应该可以:
不过,
zip
给出了一个元组列表。如果您需要列表列表,您可以执行以下任一操作:This should do:
Though,
zip
gives a list of tuples. If you need a list of lists you can do either of these:如果所有行的长度相等,则
data = zip(*maReader)
应该这样做。如果不是:
另请参阅Python 中的矩阵转置。
if all rows of equal length then
data = zip(*maReader)
should do it.If not:
See also Matrix Transpose in Python.