Python用户生成的字典名称和输入

2024-05-08 13:39:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个问题

我正在自学如何使用Python(随后是django)编写代码。我正在开发一个网站,让当地的帆船赛能够创建团队并跟踪他们的成绩。虽然这最终将是一个使用数据库的django项目,但我想编写一个简单的脚本来“勾勒”逻辑

目标:我希望用户能够创建一个比赛组,将船只添加到此组,并打印各种项目

当前代码:我编写了基本脚本,允许用户将船只添加到现有比赛组:

#basic program logic to add boats to an existing race group;

#existing race group:

shediac = {
    'location':'Shediac NB',
    'year':2020,
    'boats': boats
}

#default boat list to pass into the race group

 boats=[
    {'name':'name1','owner':'owner1','handicap':0.00},  
]

#loop to take user input when adding new entries

answer=input('do you want to add a boat?: Y/N').upper()

while answer == 'Y':

    name = input('enter the boat name: ')
    owner = input('enter the boat owner''s name: ')
    handicap = input('enter the boat handicap: ')

    boats.append({
        'name': name,
        'handicap': handicap,
        'owner': owner,
        })

    # get user input again to retest for the while loop
    answer=input('do you want to add a boat?: Y/N').upper()

#prompt user to select information to display:

while true: 

what = input('what do you want to view: NAMES / OWNERS / HANDICAP / EXIT: 
').lower()

    if what == 'names':
        for boat in shediac['boats']:
            print(boat['name'])
    elif what == 'owners':
        for boat in shediac['boats']:
            print(boat['owner'])
    elif what == 'handicap':
        for boat in shediac['boats']:
            print(boat['handicap'])
    else:
        print('see you next time')

挑战

  1. 如何让用户创建新的种族组

  2. 如何利用用户输入生成新种族组的名称

我为每个比赛组使用一个字典,并传递一个船只列表(包含各种键值对的字典)。现有代码用于将船条目添加到现有比赛组(字典)

如果我的方法完全错误,我欢迎任何更好的解决方案!我的主要兴趣是了解如何处理这样的问题

谢谢


Tags: theto代码用户nameyouforinput
1条回答
网友
1楼 · 发布于 2024-05-08 13:39:51

虽然将内容存储在字典中是可以的,但有时使用专用类型更为清晰:

from dataclasses import dataclass
from typing import List

@dataclass
class Boat:
    name: str
    owner: str
    handicap: float

@dataclass
class RaceGroup:
    location: str
    year: int
    boats: List[Boat]

接下来,定义一些输入方法。下面是一个返回Boat的方法:

def input_boat() -> Boat:
    name = input("enter the boat name: ")
    owner = input("enter the boat owner's name: ")
    handicap = float(input("enter the boat handicap: "))
    return Boat(name, owner, handicap)

现在来看一个返回Boat列表的方法。我们可以在循环中重用input_boat

def input_boat_list() -> List[Boat]:
    boats = []
    while True:
        response = input('do you want to add a boat? [Y/N]: ').upper()
        if response == "N":
            return boats
        if response == "Y":
            boat = input_boat()
            boats.append(boat)

下面是一个返回RaceGroup的方法:

def input_race_group() -> RaceGroup:
    location = input("enter the location: ")
    year = input("enter the year: ")
    boats = input_boat_list()
    return RaceGroup(location, year, boats)

当你把事情分解成子问题时,编程更容易,代码也更清晰


我们现在可以使用上面在主程序中创建的函数“库”:

default_boat_list = [
    Boat(name="name1", owner="owner1", handicap=0.00),  
]

shediac = RaceGroup(
    location="Shediac NB",
    year=2020,
    boats=list(default_boat_list),
    # list(...) creates a "shallow" copy of our earlier list
}

race_groups = [shediac]

while True:
    response = input('do you want to add a race group? [Y/N]: ').upper()
    if response == "N":
        break
    if response == "Y":
        race_group = input_race_group()
        race_group.boats = default_boat_list + race_group.boats
        race_groups.append(race_group)

print(race_groups)

相关问题 更多 >