[英]In Python, if you have two lists that share a number of elements, how do you create a new list with the matches?
[英]How do you have a user input a number and have that number pull that data cell value from a list?
對於分配給我的任務,您被告知當一個人輸入一個數字時,應從列表中提取該數據單元格值。 我如何實現這一目標?
我假設您的意思是“數據單元格值”作為索引處的“列表項”。
首先是來自用戶的輸入,使用輸入函數。 如果這不是有效整數,則int函數將引發異常。
然后我們還必須檢查用戶給出的索引是否在列表大小之內。 列表的第一個元素位於索引#0,最后一個元素是# list-length - 1。例如,3 項列表的元素位於 0、1、2。
fruit = [ "Apples", "Oranges", "Rambutan", "Mango" ]
try:
user_text = input("Enter fruit index: ")
user_choice = int(user_text)
except:
print("Bad Choice");
user_choice = -1
if (user_choice >= 0 and user_choice < len(fruit)):
print("Your Fruit is: " + fruit[user_choice])
else:
print("Index out of range")
例如:
# python3 ./fruit.py Enter fruit index: 2 Your Fruit is: Rambutan # python3 ./fruit.py Enter fruit index: None of your business Bad Choice Choice out of range
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.