提问人:Groth 提问时间:11/15/2023 最后编辑:smciGroth 更新时间:11/17/2023 访问量:45
当用户输入基于需要从列表中迭代的内容时,如何访问多个列表中的特定项目?
How can I access specific items from multiple lists when the user input is based on what needs to be iterated from the lists?
问:
我已经研究这个家庭作业问题一个星期了,我无法将我的大脑包裹在看似如此简单的事情上。我有 4 个列表,并尝试根据用户输入的内容在 for 循环中迭代每个列表中的特定项目。问题是,当我尝试从列表中访问特定项目时,它会导致输出中我想要的内容的倍数。我应该在家庭作业问题中使用集合。我不是在寻找任何人为我做这个问题,而是帮助我做错什么。我的问题是如何设置我的列表还是我的 for 循环?我应该使用元组吗...?
# List items are ordered. so all of possition [0] is information for course1.
# Position [1] is for course2 and so on.
courseID = ['course1','course2','course3','course4'] #Provided Info
room = ['room1', 'room2', 'room3', 'room4'] #Provided Info
proffessor = ['teacher1', 'teacher2', 'teacher3', 'teacher4'] #Provided Info
text = ['text1', 'text2', 'text3', 'text4'] #Provided Info
userInput = input('Enter Course Number: ') #Get User Input
for i in courseID: #For loop to cycle through the info provided
if userInput == courseID[0]:
print('room: ',room[0])
print('professor: ',[proffessor[0]])
print('Text: ', text[0])
else:
if userInput == courseID[1]:
print('room: ',room[1])
print('professor: ',[proffessor[1]])
print('Text: ', text[1])
else:
if userInput == courseID[2]:
print('room: ',room[2])
print('professor: ',[proffessor[2]])
print('Text: ', text[2])
OUTPUT=
Enter Course Number: course1
room: room1
professor: ['teacher1']
Text: text1
room: room1
professor: ['teacher1']
Text: text1
room: room1
professor: ['teacher1']
Text: text1
room: room1
professor: ['teacher1']
Text: text1
输出我正在寻找:
Enter Course Number: Course #
room: room #
professor: teacher
text: text
答:
1赞
user19077881
11/15/2023
#1
更简单地说,您可以在 courseID 中获取输入值的索引,然后使用该索引访问其他每个列表。这消除了您的 if-else 链。
courseID=['course1','course2','course3','course4'] #Provided Info
room = ['room1', 'room2', 'room3', 'room4'] #Provided Info
proffessor = ['teacher1', 'teacher2', 'teacher3', 'teacher4'] #Provided Info
text= ['text1', 'text2', 'text3', 'text4'] #Provided Info
userInput= input('Enter Course Number: ') #Get User Input
if userInput in courseID:
idx = courseID.index(userInput)
print('room ', room[idx])
print('professor ', proffessor[idx])
print('text ', text[idx])
else:
print('unknown course')
评论
0赞
Groth
11/16/2023
这绝对有效。谢谢你的回答。我很高兴有人理解我想说的话,因为我对编程非常陌生。
0赞
user19077881
11/16/2023
你做了一个很好的尝试。继续前进!一个提示 - 当你看到重复的代码(例如在你的if-else链中)时,请考虑用更少的代码替换它。不要重复自己是一个基本的口头禅。
上一个:通过VBA为每个循环着色单元格
评论
for i in courseID: ... if userInput == courseID[0]:
courseID.index(userInput)
try... except ValueError
if... elif
if... else: if...