jung
jung

Reputation: 1

Making one list that satisfies the condition

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.

Upvotes: 0

Views: 48

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122002

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.

Upvotes: 3

Related Questions