2

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.

user1013550
  • 53
  • 1
  • 4

4 Answers4

3

Here's an EAFP counterpoint to @retracile's LBYL approach.

data = [] #list()
maReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='"')
for rindex, row in enumerate(maReader):
    for iindex, item in enumerate(row):
        try:
            data[iindex].append(item)
        except IndexError:
            data.append([item])
Marty
  • 7,920
  • 1
  • 20
  • 10
2

Assuming all rows of equal length, you can approach it like this:

data = list()
maReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='"')
for rindex, row in enumerate(maReader):
    for iindex, item in enumerate(row):
        if len(data) <= iindex:
            data.append([])
        data[iindex].append(item)
retracile
  • 12,167
  • 4
  • 35
  • 42
2

This should do:

maReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='"')
data = zip(*maReader)

Though, zip gives a list of tuples. If you need a list of lists you can do either of these:

data = [list(x) for x in zip(*maReader)]
data = map(list, zip(*maReader))
Avaris
  • 35,883
  • 7
  • 81
  • 72
1

if all rows of equal length then data = zip(*maReader) should do it. If not:

from itertools import izip_longest

list(izip_longest(*f, fillvalue=''))

See also Matrix Transpose in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670