How to get rows and columns from text block

Question:

Hi I have following text block:

abcd
efgh
ijkl
mnop

I want to put columns and rows in different lists. I managed to make rows list because it is obvious but still struggling with columns.

rowsList = []
columnsList = []
block = open("asd.txt", "r").read().split('n')
for line in block:
    rowsList.append(line)

#['abcd', 'efgh', 'ijkl']

for i in range(len(rowsList)):
    for j in range(len(rowsList[i])):
        ???
Asked By: Sosek

||

Answers:

You can use zip to achieve "transposing":

with open('asd.txt', 'r') as f:
    rows = f.read().splitlines()

cols = [''.join(zipped) for zipped in zip(*rows)]

print(rows) # ['abcd', 'efgh', 'ijkl', 'mnop']
print(cols) # ['aeim', 'bfjn', 'cgko', 'dhlp']

zip(*rows) would be equivalent to zip('abcd', 'efgh', 'ijkl', 'mnop'). At the first iteration in the list comprehension as an example, zipped will be ('a', 'e', 'i', 'm') (a tuple consisting of the first characters in each row). ''.join(zipped) then yields 'aeim'.

If you prefer to use for with index-based idiom, the following basically achieves the same. However, this is generally not recommended (not pythonic!):

cols = []
for i in range(len(rows)):
    col = []
    for j in range(len(rows[i])):
        col.append(rows[j][i])
    cols.append(''.join(col))
Answered By: j1-lee

You are completely correct right now. You just access the column as rowsList[i][j].

Answered By: 2pichar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.