簡體   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