不能完全確認消息發送到用戶應該是什麼你想要的是範圍環和遍歷他random_things話:
random_things=['food', 'room', 'drink', 'pet']
# store all the lists of input
output = []
# loop 7 times
for _ in range(7):
# new list for each set of input
temp = []
# for each word in random_things
for word in random_things:
# ask user to input a related word/phrase
temp.append(input("Choose something related to {}".format(word)))
output.append(temp)
取而代之的是temp
列表,你可以使用一個list comprehension:
random_things = ['food', 'room', 'drink', 'pet']
output = []
for _ in range(7):
output.append([input("Choose something related to {}".format(word)) for word in random_things])
這可能是合併成一個單一的列表理解:
output = [[input("Choose something related to {}".format(w)) for w in random_things]
for _ in range(7)]
如果你必須使用一個計數變量,你可以使用while循環:
random_things=['food', 'room', 'drink', 'pet']
# store all the lists of input
output = []
# set count to 0
count = 0
# loop seven times
while count < 7:
# new list for each set of input
temp = []
index = 0
# loop until index is < the length of random_things
while index < len(random_things):
# ask user to input a related word/phrase
# use index to access word in random_thongs
temp.append(input("Choose something related to {}".format(random_things[index])))
index += 1
output.append(temp)
# increase count after each inner loop
count += 1
列表索引從0開始,因此第一個元素是在索引0處沒有索引1.
'format(w)'有什麼用?謝謝! – Francisunoxx
@MiaLegaspi,第一次迭代會輸出'選擇與食物相關的東西',第二'選擇與房間相關的東西'等。 –
有沒有一種方法可以使用計數器而不是for循環?像random_things + = 1或者是不可能的? –