[英]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.