簡體   English   中英

Python - 用戶生成的字典名稱和輸入

[英]Python - User generated dictionary names and input

這是我的第一個 SO 問題。

我正在自學使用 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. 如何根據用戶輸入生成新種族組的名稱

我為每個種族組使用一個字典,並傳入一個船列表(包含各種鍵值對的字典)。 現有代碼用於將船只條目添加到現有種族組(字典)。

如果我的方法完全錯誤,我歡迎任何更好的解決方案! 我的主要興趣是了解如何解決這樣的問題。

謝謝。

雖然將內容存儲在字典中很好,但有時使用專用類型會更清晰:

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)

暫無
暫無

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

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