简体   繁体   English

无法计算对象列表中的属性

[英]Unable to count an attribute in a list of objects

Disclaimer: New to python免责声明: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. object 的列表打印得很好,但是事实证明,试图计算每个学生来自的国家/地区很困难。

Below is the txt file i am reading from, the class i have set up and the code.下面是我正在阅读的 txt 文件,我设置的 class 和代码。 Any help would be greatly appreciated.任何帮助将不胜感激。 I have attached a screenshot of the output at the bottom.我在底部附上了 output 的截图。

(I have had to space of the data from the text file) (我不得不从文本文件中获取数据空间)

B123, Jones, Barry, 24, Wales B123,琼斯,巴里,24 岁,威尔士

B134, Kerry, Jane, 21, Scotland B134,Kerry,Jane,21 岁,苏格兰

B456, Smith, Percy, 19, England B456,史密斯,珀西,19 岁,英格兰

B788, Roberts, Mary, 20, England B788,罗伯茨,玛丽,20 岁,英格兰

B543, Brown, Sinead, 22, Scotland B543, Brown, Sinead, 22, 苏格兰

B777, Wilson, Rachel, 24, Wales B777,Wilson,Rachel,24 岁,威尔士

B321, Taylor, Peter, 20, England B321,泰勒,彼得,20 岁,英格兰

B448, Anderson, Jill, 18, England B448,安德森,吉尔,18 岁,英格兰

B999, Moore, Misty, 20, Wales B999, Moore, Misty, 20, 威尔士

B278, Jackson, Bob, 23, Scotland B278,Jackson,鲍勃,23 岁,苏格兰


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) Output 用于打印(studentObj)

It looks like whitespace characters could be causing the if statements to always return false.看起来空格字符可能导致 if 语句始终返回 false。 Try using the .strip() function:尝试使用.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. “blankpaper.txt”是一个文件,其中粘贴了您提供的文本。该程序使用counts字典按国家/地区存储观察次数。 The program reads the file, line-by-line.程序逐行读取文件。 For each line, the count for the corresponding country is incremented in counts .对于每一行,相应国家/地区的计数以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).为了说明这一点,片段 2 说明了如何从文件中计算最小和最大年龄(同时还计算了按国家/地区的观察次数)。

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)片段 1 (按国家/地区统计观察结果)


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 Output


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

Snippet 2 (counts observations by country and computes max and min ages)片段 2 (按国家/地区统计观察结果并计算最大和最小年龄)


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 Output


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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