簡體   English   中英

從用戶輸入的列表中刪除名稱,並平均成績

[英]deleting a name from a list input by user and averaging a class score

我已經閱讀了很多關於Python的教程,並且目前正在使用python進行編程類的入門,但是我無法弄清楚。 我已經搜索了堆棧溢出,dani網站,java2s,github和許多其他內容,但無法理解我在做什么錯。

這是我編程班上的最后一個項目,我想在課堂上做幾件事,然后將它們導入主程序。

最終,我希望也可以在我的工作場所中使用它,並希望它向用戶提供選項菜單。 1:添加名稱和鍵入速度。 2:按值刪除姓名(學生的姓名,如果可能的話,我想在課堂上做這件事。3:打印姓名和速度。4:打印速度列表。5:打印平均值速度列表中的速度(我也想在課堂上做),並退出程序6。

我試圖變得雄心勃勃,並創建了一個隨機的名稱生成器,所以我也創建了一個打印名稱列表的函數,但這要在星期一早上進行,所以由於沒有時間,我取消了該項目。

無效的部分是#2-刪除名稱和#3-平均分數。 在#2上,我沒有嘗試過.remove,del或其他任何我見過的人嘗試過的事情。 似乎大多數示例僅是硬編碼的。其他示例對我而言沒有意義。 在#3上,我嘗試了多種計算,包括將數字分別加在一起,創建不同的函數並除以len,還嘗試了均值Built_in。

我可以根據工作情況進行分配,但是其他部分對將其用於特定目的特別有用。

這是我的課程:

class student_info:

    def __init__(self):
        self.name = ""
        self.speed = ""
        self.speed_average = 0

def speed_average(self):
    return sum(self.speed) / len(self.speed)

和主程序(帶注釋):

import studentClass

name_list = []
speed = 0

def edit_list(name):
    new_name = input("What is the student's name? ")
    if new_name != "":
        name.name = new_name

    while True:
        try:
            typing_speed = input("What was the last typing speed? ")
            if speed != "":
                name.speed = float(typing_speed)
                #print (test_score)
            else:
                raise ValueError
            break
        except ValueError:
            print("Not a valid score.")

def print_students(list):
    for i, n in enumerate(list):
        print("#%d: Name: %s, Typing Speed (wpm): %d" % (i+1, n.name, n.speed))

def print_speed(list):
    for i, n in enumerate(list):
        print("%s" % (n.speed))

##Since the class instantiation didn't work, I tried creating a function - that didn't work either.
def print_avg(list):
    speed_list = speed
    print(sum(speed)/len(speed))

while True:
    print("Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit")
    choice = input(" >> ")
    if choice == '1':
        name_list.append(studentClass.student_info())
        edit_list(name_list[-1])
    elif choice == '2':
        names = [name_list]       
        del_name = input("What name would you like to remove? ")
        name_list.remove(del_name)
        if del_name not in name_list:
            print("Name not found.")
        else:
            print("%s removed." % del_name)
    elif choice == '3':
        print_students(name_list)           
    elif choice == '4':
        print_speed(name_list)
    elif choice == '5':
        class_avg = studentClass.student_info()
        print("Average score for class: " %(class_avg.speed_average))
    elif choice == '6':
        print('Happy Typing!')
        break
    else:
        print("That's not an option. Please try again.")



Error returned when #2 is selected:
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 1
What is the student's name? john
What was the last typing speed? 20
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 1
What is the student's name? mary
What was the last typing speed? 10
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 4
20.0
10.0
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 3
#1: Name: john, Typing Speed (wpm): 20
#2: Name: mary, Typing Speed (wpm): 10
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 2
What name would you like to remove? john
Traceback (most recent call last):
  File "C:\Users\Whited\Desktop\Classes\Programming\studentRun.py", line 44, in <module>
    name_list.remove(del_name)
ValueError: list.remove(x): x not in list
>>>



Error returned when #5 is selected:

    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 1
    What is the student's name? john
    What was the last typing speed? 20
    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 1
    What is the student's name? mary
    What was the last typing speed? 10
    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 5
    Traceback (most recent call last):
      File "C:\Users\Whited\Desktop\Classes\Programming\studentRun.py", line 56, in <module>
        print("Average score for class: " %(class_avg.speed_average))
    TypeError: not all arguments converted during string formatting
    >>> 

其他一切都按預期運行。 如果有人可以幫助我解決這個問題,我將不勝感激。 謝謝!

更新:以適當的縮進和調用來運行5。

追溯(最近一次通話):文件“ C:\\ Users \\ Whited \\ Desktop \\ Classes \\ Programming \\ studentRun.py”,行56,在打印中(“類的平均分數:“%(class_avg.speed_average())) TypeError:“ int”對象不可調用

更新:順便使用Python 3。 -並且,該文件另存為studentClass

我很無聊,而且有點嗡嗡作響,所以我想我只想拋出一些可以從中學習的工作代碼:

# A Student object will just take care of tracking the name and speed.
# Classes like this in Python (with no methods) are often better represented
# by a namedtuple from the collections package.
class Student(object):

    def __init__(self, name="", speed=0):
        self.name = name
        self.speed = speed

# The Class object will represent a group of students.
# The students are tracked via a dictionary where the key is the name of 
# the student and the value is the Student object.
class Class(object):

    def __init__(self):
        """ Create an empty dictionary for the students """
        self.students = {}

    def add_student(self, student):
        """ Add a student to the "roster".  The student name will be the 
            key and the Student instance will be the value """
        self.students[student.name] = student

    def remove_student(self, name):
        """ Remove a student if they exist.  If they exist and are removed
            return True.  If they do not exist, return False """
        if name in self.students:
            del self.students[name]
            return True
        return False

    def average(self):
        """ Get the average speed of the students.
            The self.student.values() will be the values of the self.students
            dictionary, which means it will be a list of students.
            For each of the students, get their speed.  Sum those speeds
            and divide by the number of students.
            The fancy syntax of [x for x in y] below is called a list comprehension """
        return sum(student.speed for student in self.students.values()) / len(self.students)

def print_students(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Name: %s, Typing Speed (wpm): %d" % (i+1, student.name, student.speed))

def print_speed(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Typing Speed (wpm): %d" % (i+1, student.speed))


def add_student(group):
    new_name = ""
    typing_speed = None
    while not new_name:
        new_name = input("What is the student's name? ")
    while typing_speed in ("", None):
        typing_speed = input("What was the last typing speed? ")
        try:
            typing_speed = float(typing_speed)
        except:
            print("Please enter a number")
            typing_speed = None
            continue
    # We have a valid name and value speed, so create a Student and add them to the Class
    group.add_student(Student(new_name, typing_speed))


if __name__ == "__main__":
    group = Class()

    while True:
        print("Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit")
        choice = input(" >> ")

        if choice == '1':
            add_student(group)
            continue

        if choice == '2':
            del_name = input("What name would you like to remove? ")
            if group.remove_student(del_name):
                print("%s removed." % del_name)
            else:
                print("Name not found.")
            continue

        if choice == '3':
            print_students(group)
            continue

        if choice == '4':
            print_speed(group)
            continue

        if choice == '5':
            print("Average score for class: %0.2f" %(group.average()))
            continue

        if choice == '6':
            print('Happy Typing!')
            break

        print("That's not an option. Please try again.")

我更喜歡if =>在這種情況下繼續,而不是if,elif ...

使用班級(粗略地命名)來管理學生(添加和刪除)並取其平均值是一種很好的方法。

至於你做錯了什么:

  1. 刪除學生。

您的name_list不是名稱列表,它是student_info的列表。 您嘗試先從列表中remove該名稱,然后再檢查該名稱是否在其中,因此這將始終失敗。 至少您要在調用remove之前檢查是否存在。 但這對您永遠不會起作用,因為列表不包含字符串,而是包含student_info 要使您的工作正常,您需要做類似的事情

found = False
for i, student in enumerate(name_list):
    if student.name == del_name:
        found = i
if found != False:
    del name_list[found]
    print("Deleted...")
else:
    print("Could not find name %s" % (del_name,))
  1. 取平均值:

您正在做的是創建一個Student_info的新的空實例。 您要做的就是獲取現有學生的價值。

total_score = 0
for student in name_list:
    total_score += student.speed
average = total_score / len(name_list)

在評論中回答您的問題:

  1. 所有類都應從對象繼承(新樣式類) https://wiki.python.org/moin/NewClassVsClassicClass

  2. values是一種獲取字典的方法。

    {"1": ['a', 'b'], "foo", 10.0}.values() == [["a", "b"], 10.0]

  3. 只需將Student和Class類復制到另一個文件(例如,使用models.py),然后執行以下任一操作:

    import models

然后,在任何使用“學生”或“班級”(在models.py之外)的地方,都使用模型作為前綴。 喜歡

group = models.Class()
...
group.append(models.Student(new_name, typing_speed))

或者你可能只有

from models import *

這會將所有內容從models.py導入當前名稱空間,因此無需更改其他代碼。 保留名稱空間是一個好主意...所以我會選擇選項1。

  1. 名稱==主要內容...
if __name__ == "__main__"

最好在每個文件中都包含此內容。 執行python程序時,執行的文件名為main ”。 此檢查將告訴您是否正在執行文件。 如果您的文件是通過其他方式導入的,則名稱將不是“ main ”。 這使您可以根據執行還是導入來執行不同的操作。

我認為您本可以使用字典來解決這個問題。

另外,您還有一個成員speed_average和一個成員函數speed_average。 函數和變量的名稱不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM