0

I'm a beginner and I am stuck at this practice exercise. I am not allowed to use any modules to solve this problem. I have a csv file with 10 rows representing a different house in each row and 20 columns representing days. For each day, it was recorded whether the temperature in a house fell below 15 deg C. There is no header to the file.

0,2,4,1,1,2,...
2,2,2,1,1,0,...
1,1,1,2,0,0,...
...

I need to perform some calculations such as the average number of times the temp fell below 15 deg C per house and per day. So I'm thinking I need a list of houses which contains all the rows as lists and a list of days which contains sorted values of the correlative columns like [[0,2,1,...],[2,2,1,...],...] to perform these calculations. So far I have tried

file = open("filename.csv")
days = []
for line in file:
    line = line.strip()
    data = line.split(",")
    for x in range(0, len(data)):
        days.append(int(data[x]))
print(days)

This is not giving me the list of days like I hoped for. I am getting one big list with all the data in it. What am I doing wrong?

1 Answer 1

1

I think that the effective way you can do it like this:

days = []
with open('filename.csv') as file:
    lines = file.readlines()
    for line in lines:
         line = line.strip() ##Remove space and newline
         numbers = line.split(',')
         days.append(numbers)

print(days)
Sign up to request clarification or add additional context in comments.

2 Comments

Firstly this is giving me the list in string but even if I convert number to int I am still getting the same result as with my code. I need the days list to be a list of each column. So the output for days should be [[0,2,1,...],[2,2,1,...],...] but I'm getting [0,2,4,1,1...1,1,1,2,0,0...]. This is the whole data as one big list.
@SamRa So it can be more easy, I have updated my code

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.