简体   繁体   English

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

[英]Python - User generated dictionary names and input

This is my first SO question.这是我的第一个 SO 问题。

I am teaching myself to code using Python (and subsequently django).我正在自学使用 Python(以及随后的 django)编写代码。 I am working on developing a website that allows local sailing regattas to create groups and track their results.我正在开发一个网站,允许当地帆船赛创建团体并跟踪他们的结果。 Although this will eventually be a django project using a database, I wanted to write a simple script to 'sketch' the logic.虽然这最终将是一个使用数据库的 django 项目,但我想编写一个简单的脚本来“绘制”逻辑。

Objective : I would like a user to be able to create a Race Group, add boats to this group, and print various items.目标:我希望用户能够创建一个种族组,向该组添加船只,并打印各种项目。

Current Code : I have written the basic script that allows users to add boats to an existing race group:当前代码:我编写了允许用户将船只添加到现有比赛组的基本脚本:

#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')

Challenge :挑战

  1. How do I get a user to create a new race group如何让用户创建新的种族组

  2. How do I take the user input to generate the name of the new race group如何根据用户输入生成新种族组的名称

I am using a dictionary for each race group, and passing in a list of boats (dictionaries containing various key value pairs).我为每个种族组使用一个字典,并传入一个船列表(包含各种键值对的字典)。 The existing code works to add boat entries to the existing race group (dictionary).现有代码用于将船只条目添加到现有种族组(字典)。

If my approach is entirely wrong, I welcome any better solutions!如果我的方法完全错误,我欢迎任何更好的解决方案! My primary interest is understanding how to approach such a problem.我的主要兴趣是了解如何解决这样的问题。

Thanks.谢谢。

While storing things inside dictionaries is fine, it's sometimes clearer to have dedicated types:虽然将内容存储在字典中很好,但有时使用专用类型会更清晰:

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]

Next up, define a some input methods.接下来,定义一些输入法。 Here's a method that returns a 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)

Now for a method that returns a list of Boat s.现在返回一个返回Boat列表的方法。 We can reuse input_boat here inside a loop:我们可以在循环中重用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)

Here's a method that returns a RaceGroup :这是一个返回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)

Programming is easier and code becomes clearer when you break things up into subproblems!当你把事情分解成子问题时,编程更容易,代码也更清晰!


We can now use the "library" of functions that we've created above in our main program:我们现在可以在主程序中使用上面创建的函数“库”:

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)

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

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