2016-04-02 55 views
0

我有一個任務,我被要求重複一個列表,但不同的"items"(我想你會這麼稱呼它)。我如何在列表中使用用戶輸入

,我似乎是搞清楚如何與用戶input改變list以及如何使用像一個counter

我應該改變的唯一問題: random_things=['food', 'room', 'drink', 'pet']

到: random_things=['apple', 'bedroom', 'apple juice', 'dog']

但我必須這樣做7次,所以我需要能夠保持分開列出像random_things[1]random things[2]etc

我在11級,所以請儘量保持簡單,你可能可以,因爲這是我第一年編碼

回答

0

不能完全確認消息發送到用戶應該是什麼你想要的是範圍環和遍歷他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.

+0

'format(w)'有什麼用?謝謝! – Francisunoxx

+0

@MiaLegaspi,第一次迭代會輸出'選擇與食物相關的東西',第二'選擇與房間相關的東西'等。 –

+0

有沒有一種方法可以使用計數器而不是for循環?像random_things + = 1或者是不可能的? –

相關問題