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

5
  • 1
    Its easily doable in python however I suggest you to have a look at pandas. Commented Mar 6, 2019 at 19:23
  • Numpy also has functions to make this very simple if you're open to going outside "pure" python Commented Mar 6, 2019 at 19:24
  • I believe my teacher wants us to use pure python Commented Mar 6, 2019 at 19:27
  • For homework questions you should always specify that it is a homework question and the relevant restrictions. Commented Mar 6, 2019 at 20:15
  • OP has specified homework and restrictions in the original question "My teacher wants us to use pure python, so no add ons like panda or numpy." -- is pretty clear. Commented Mar 6, 2019 at 20:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.