簡體   English   中英

如何打印用戶從該列表中輸入名稱的完整列表? PYTHON

[英]How do I print a full list where a user has input a name from that list? PYTHON

我已經能夠找到大量有關從列表中選擇值的信息,但我想從其中包含的值中選擇一個列表。 問題是我不希望它像做一堆 ' if那樣冗長,因為那是矯枉過正。

有沒有辦法使用該值打印整個列表? 這是為了幫助我以后的計算課程。 我應該從前幾年就知道這一點,但由於我課程的性質,我的同齡人可能不知道。

這是相關代碼:

Doggo_Database = [['Lilly', 'Jack Russell', 'White', 'F', 2009, 'Medium'],
                  ['Winston', 'Pug', 'Brown', 'M', 2010, 'Small'],
                  ['Bo', 'Doberman', 'Brown', 'M', 2011, 'Large'],
                  ['Shep', 'Border Collie', 'Black', 'M', 2006, 'Large'],
                  ['Rodney', 'Jack Russell', 'Grey', 'F', 2010, 'Medium'],
                  ['Butch', 'Bulldog', 'White', 'F', 2011, 'Medium'],
                  ['Sally', 'Boston Terrier', 'Brown', 'F', 2013, 'Small']]
names = [Doggo_Database[0][0], Doggo_Database[1][0], Doggo_Database[2][0], Doggo_Database[3][0], Doggo_Database[4][0], Doggo_Database[5][0], Doggo_Database[6][0]]
name_select = input('Do you know the name of the Doggo? If yes, state the name. If no, state NO in capital letters. ')
while name_select != 'NO' and name_select not in names:
    print('This is not a valid entry.')
    name_select = input('Please try again: ')
    
if name_select != 'NO':
    for name in names:
        if name_select == name:
            print(name_select)
            Data_name = 
elif name_select == 'NO':
    print("We're currenly unable to find the doggo until more search options are availble")
else:
    print('a logic error has occurred')

我為此使用基礎 python,而不是 SQL

Data_name =您正在尋找Data_name =相應列表 鑒於您的代碼編寫方式,您可以這樣做:

Data_name = [i for i in Doggo_Database if i[0]==name_select][0]

例如如果name_select = 'Bo'

結果將是

['Bo', 'Doberman', 'Brown', 'M', 2011, 'Large']

如果您可以使用 python dict (作為狗 DB),它將使您的代碼更清晰。

db = {'Lilly': ['Jack Russell', 'White', 'F', 2009, 'Medium'],
      'Winston': ['Pug', 'Brown', 'M', 2010, 'Small']}

name_select = input('Do you know the name of the Doggo? If yes, state the name. If no, state NO in capital letters. ')
while name_select != 'NO' and name_select not in db:
    print('This is not a valid entry.')
    name_select = input('Please try again: ')

if name_select != 'NO':
    print(f'Dog details: {db.get(name_select)}')
else:
    print("We're currenly unable to find the doggo until more search options are availble")

暫無
暫無

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

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