简体   繁体   中英

Unable to count an attribute in a list of objects

Disclaimer: New to python

I am trying to print out a count of attributes from a list of objects, and when i try to run it, the count comes back as zero. The list of object prints fine, however trying to count the countries each student is from is proving difficult.

Below is the txt file i am reading from, the class i have set up and the code. Any help would be greatly appreciated. I have attached a screenshot of the output at the bottom.

(I have had to space of the data from the text file)

B123, Jones, Barry, 24, Wales

B134, Kerry, Jane, 21, Scotland

B456, Smith, Percy, 19, England

B788, Roberts, Mary, 20, England

B543, Brown, Sinead, 22, Scotland

B777, Wilson, Rachel, 24, Wales

B321, Taylor, Peter, 20, England

B448, Anderson, Jill, 18, England

B999, Moore, Misty, 20, Wales

B278, Jackson, Bob, 23, Scotland


class Student:

    def __init__(self, student_id, surname, forename, age, country):
        self.student_id = student_id
        self.surname = surname
        self.forename = forename
        self.age = age
        self.country = country

    def printStudentDetails(self):
        print("StudentID: ", self.student_id)
        print("Surname: ", self.surname)
        print("Forename: ", self.forename)
        print("Age: ", self.age)
        print("Country: ", self.country)

from Student import *

students_list = []

students_text = open("studentsText.txt", "r")

for line in students_text:
    split_line = line.split(", ")
    students = Student(*split_line)
    students_list.append(students)

students_text.close()


def print_students1():

    english_count = 0
    scotland_count = 0
    wales_count = 0

    for studentObj in students_list:
        studentObj.printStudentDetails()

        if studentObj.country == "England":
            english_count += 1

        elif studentObj.country == "Scotland":
            scotland_count += 1

        elif studentObj.country == "Wales":
            wales_count += 1

    print("The amount of students is ", len(students_list))
    print("English Students: ", english_count)
    print("Scottish Students: ", scotland_count)
    print("Welsh Students: ", wales_count)

输出

输出满

Output for print(studentObj)

It looks like whitespace characters could be causing the if statements to always return false. Try using the .strip() function:

        if studentObj.country.strip() == "England":
            english_count += 1

        elif studentObj.country.strip() == "Scotland":
            scotland_count += 1

        elif studentObj.country.strip() == "Wales":
            wales_count += 1

The following could be helpful. "blankpaper.txt" is a file with the text you provided pasted in. The program uses a counts dictionary to store the number of observations by country. The program reads the file, line-by-line. For each line, the count for the corresponding country is incremented in counts .

The code is designed so that if you need to make use of information in more than one column (presently we only need information from the last column) then it would be easy to modify. To illustrate this, snippet 2 illustrates how to also compute the min and max ages from the file (while also counting the number of observations by country).

I hope this helps. If there are any questions and/or if there is any way that you think I can help please let me know!

Snippet 1 (counts observations by country)


import csv

# dictionary to store number of observations by country
counts = {"Wales": 0, "England": 0, "Scotland": 0}

with open("blankpaper.txt", newline = '') as f:
    # returns reader object used to iterate over lines of f
    spamreader = csv.reader(f, delimiter = ',')

    # each row read from file is returned as a list of strings
    for index_a, row in enumerate(spamreader):
        # reversed() returns reverse iterator (start from end of list of str)
        for index_b, i in enumerate(reversed(row)):
            # if last element of line (where countries are)
            if index_b == 0:
                for key in counts:
                    if key in i:
                        counts[key] += 1
                        break
                break


print(f"Counts: {counts}")

Output


Counts: {'Wales': 3, 'England': 4, 'Scotland': 3}

Snippet 2 (counts observations by country and computes max and min ages)


import csv

# dictionary to store number of observations by country
counts = {"Wales": 0, "England": 0, "Scotland": 0}

with open("blankpaper.txt", newline = '') as f:
    # returns reader object used to iterate over lines of f
    spamreader = csv.reader(f, delimiter = ',')

    # each row read from file is returned as a list of strings
    for index_a, row in enumerate(spamreader):
        # reversed() returns reverse iterator (start from end of list of str)
        for index_b, i in enumerate(reversed(row)):
            # if last element of line (where countries are)
            if index_b == 0:
                for key in counts:
                    if key in i:
                        counts[key] += 1
                        break
                continue

            # second to last element of line
            i = int(i)
            # if first line, second to last element
            if index_a == 0:
                # initialize max_age and min_age
                max_age = min_age = i

            break

        #print(row)
        # if encounter an age greater than current max, make that the max
        if i > max_age:
            max_age = i
        # if encounter an age less than current min, make that the min
        if i < min_age:
            min_age = i

print(f"\nMax age from file: {max_age}")
print(f"Min age from file: {min_age}")
print(f"Counts: {counts}")

Output


Max age from file: 24
Min age from file: 18
Counts: {'Wales': 3, 'England': 4, 'Scotland': 3}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM