0

I have a CSV file containing the following data:

1,1,3,2,2,1
2,1,3,2,1,1
3,2,4,2,7,3
4,1,3,2,3,1
5,3,3,1,1,1

and I would like to create a list that has the elements of sixth column which has 1 for second column. In short, the end result I would like is [1, 1, 1]

Here is the code I wrote:

input = open("C:\\test.txt", "r")
for line in input.readlines():
 line = line.strip()
 no, grade, gpa, sex, preview, review = line.split(',')
 listno1 = []
 a = float(grade)
 if a == 1:
 listno1.append(int(review))

When I print, it turns out like this:

[]
[]
[]
[]
[1]
[2]
[]
[]
[4]
[]

Help please? And I would kind of like to stick to using lists.

Brian Tompsett - 汤莱恩
5,92772 gold badges63 silver badges135 bronze badges
asked Dec 19, 2014 at 22:59
1
  • You have listno1 = [] inside the loop, so you're clearing it every time through. Commented Dec 19, 2014 at 23:11

1 Answer 1

3

You are creating your list for each row, rather than create the list just once outside the loop.

You are also reinventing the CSV wheel; use the csv module instead. Because you are picking just the one column for each row where a condition is met, you can use a list comprehension:

import csv
with open("C:\\test.txt", "r") as infile:
 reader = csv.reader(infile)
 listno1 = [int(row[5]) for row in reader if int(row[1]) == 1]

This basically does the same thing as:

import csv
with open("C:\\test.txt", "r") as infile:
 reader = csv.reader(infile)
 listno1 = []
 for no, grade, gpa, sex, preview, review in reader:
 grade = int(grade)
 if grade == 1:
 listno1.append(int(review))

but in more compact notation.

answered Dec 19, 2014 at 23:03
Sign up to request clarification or add additional context in comments.

1 Comment

more compact to use if grade == "1" without casting to an int

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.