繁体   English   中英

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

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

免责声明:python新手

我试图从对象列表中打印出属性计数,当我尝试运行它时,计数返回为零。 object 的列表打印得很好,但是事实证明,试图计算每个学生来自的国家/地区很困难。

下面是我正在阅读的 txt 文件,我设置的 class 和代码。 任何帮助将不胜感激。 我在底部附上了 output 的截图。

(我不得不从文本文件中获取数据空间)

B123,琼斯,巴里,24 岁,威尔士

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

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

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

B543, Brown, Sinead, 22, 苏格兰

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

B321,泰勒,彼得,20 岁,英格兰

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

B999, Moore, Misty, 20, 威尔士

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

看起来空格字符可能导致 if 语句始终返回 false。 尝试使用.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

以下内容可能会有所帮助。 “blankpaper.txt”是一个文件,其中粘贴了您提供的文本。该程序使用counts字典按国家/地区存储观察次数。 程序逐行读取文件。 对于每一行,相应国家/地区的计数以counts递增。

代码的设计使得如果您需要使用多列中的信息(目前我们只需要最后一列中的信息),那么修改起来很容易。 为了说明这一点,片段 2 说明了如何从文件中计算最小和最大年龄(同时还计算了按国家/地区的观察次数)。

我希望这有帮助。 如果有任何问题和/或如果您认为我可以提供任何帮助,请告诉我!

片段 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


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

片段 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


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