2

I have a text file that contains 8 columns, like so

100 40 37 98 47 55 75 67
50 84 93 67 85 90 42 57
68 95 74 75 87 95 32 86

For my function, I need to find averages and such for all the columns, for when specified. So to do this I need to be able to work with columns, and I'm not sure how to convert all the columns into lists.

f=open(file,"r")
lines=f.readlines()
result=[]
for i in lines:
    result.append(i.split(' ')[1])
f.close()

I only have this to extract 1 column, but I would appreciate if someone could help me extract every column. My teacher wants us to use pure python, so no add ons like panda or numpy. Thanks

Joey Jordan
  • 37
  • 1
  • 4

2 Answers2

1

I would recommend extracting the rows and then transposing the resulting list of lists:

with open(filename) as f:
   columns = list(zip(*(map(int, row.split()) for row in f)))

I can help explain any part of this if you want.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
1
f = open(filename,"r")

lines = []

for line in f:
    lines.append(map(int, line.strip().split()))

f.close()

Now we have a list of lists of integers:

print(lines)
# [[100, 40, 37, 98, 47, 55, 75, 67], [50, 84, 93, 67, 85, 90, 42, 57], [68, 95, 74, 75, 87, 95, 32, 86]]

Converting lists of rows to lists of columns is referred to as "transposing" so using this answer Transpose list of lists we can get the result:

result = map(list, zip(*lines))

print(result)
# [[100, 50, 68], [40, 84, 95], [37, 93, 74], [98, 67, 75], [47, 85, 87], [55, 90, 95], [75, 42, 32], [67, 57, 86]]