1

I'm trying to read a text file. I need to read column values to list. My text file looks like this:

40 10 5 5
30 20 10 0
30 30 10 5

and desired output is

(40,30,30),(10,20,30),(5,10,10),(5,0,5)

I tried this code

def contest(filename):
    contestFile = open(filename,'r')
    contestFileLines=contestFile.readlines()
    startColumn = 0
    contestResult=[]
    for x in contestFileLines:
        contestResult.append(x.split()[startColumn])
        
    contestFile.close()
    print(contestResult)
    
contest("testing.txt")

and its output is just

['40', '30', '30']

What should I do?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
fifauser
  • 51
  • 4
  • I don't understand your need. You wrote the code you needed to do what you want. – Kwright02 Dec 27 '22 at 22:56
  • `[startColumn]` is just putting the first column in the list, not all the columns. Get rid of that. Then at the end of the loop you can transpose the 2-dimensional list to the order that you want. – Barmar Dec 27 '22 at 22:58
  • 2
    See https://stackoverflow.com/questions/6473679/transpose-list-of-lists for how to transpose a list of lists. – Barmar Dec 27 '22 at 23:00

1 Answers1

1

Try reading every line into an list, splitting by each space and mapping to an int. Then, you can use this answer (which Barmar suggested in the comments) to transpose the list of map generators. Just like this:

def cols(path):
    rows = []
    with open(path) as f:
        for line in f:
            rows.append(map(int, line.split(' ')))
    return list(map(list, zip(*rows)))


print(cols('test.txt'))  # => [[40, 30, 30], [10, 20, 30], [5, 10, 10], [5, 0, 5]]

Alternatively, if you need the output as a tuple, just change this line:

return list(map(list, zip(*rows)))

to

return list(map(tuple, zip(*rows)))
Michael M.
  • 10,486
  • 9
  • 18
  • 34