[英]Can't figure out how to reassign an element in a list of lists in this Python code
[英]Can't figure out how to assign a number to a element in a list in python
我是一個相對較新的程序員,我無法弄清楚如何為列表中的某些元素創建變量。 我正在嘗試這樣做,以便我可以要求某個數字,然后控制台將打印列表中的某個元素。 這是我必須為練習做的事情,然后才能進入下一個級別的 Python。 這種編程是通過一個叫做 codester 的網站完成的。
以下是我制作這個程序的指示:
這是我到目前為止的代碼:
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for x in mylist:
print(x)
mylist.append(input("Please enter a food number:"))
謝謝你的幫助。
看起來您正在嘗試遍歷列表的索引。 使用range
這樣做:
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for i in range(len(mylist)):
print(mylist[i])
同樣,您可以要求用戶輸入並打印特定索引:
while True:
# Ask for input
idx = input('Which food do you want to see?')
# only allow numbers
if not idx or not idx.isnumeric():
print('Please enter a valid number')
continue
# convert to int
idx = int(idx)
# more validation – only accept numbers in valid range
if idx<0 or idx>=len(mylist):
print(f'Please enter a number between 0 and {len(mylist)-1}')
continue
# otherwise
print(f'Your food is: {mylist[idx]}')
break
正如@ybressler-simon 所指出的,這些指令引用了一個索引變量,因為列表中的項目可以通過它們在列表中的位置來訪問,而按位置挑選項目的變量通常稱為索引。
>>> mylist = ['hotdish', 'lutefisk']
>>> mylist[0]
'hotdish'
>>> mylist[1]
'lutefisk'
>>> x = 0
>>> mylist[x]
'hotdish'
使用 len() 函數獲取列表中的項目數及其長度。
>>> len(mylist)
2
使用 range() 函數生成一個從 0 開始計數的數字序列。
>>> list(range(2))
[0, 1]
然后把零件放在一起,你就准備好了!
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for count, value in enumerate(mylist, start=1):
print('{} - {}'.format(count, value))
choice = int(input("Please enter a food number: "))
print(mylist[choice-1])
將導致:
1 - 櫻桃
2 - 蛋糕
3 - 米飯
4 - 香蕉
5 - 草莓
請輸入食品編號:5
草莓
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.