簡體   English   中英

如何使用列表中的用戶輸入

[英]How do i use User input in a list

我有一個作業,要求我重復一個清單,但要使用不同的"items" (我想你會這樣稱呼)。

我似乎唯一的問題是弄清楚如何通過用戶input更改list以及如何使用counter

我應該更改: random_things=['food', 'room', 'drink', 'pet']

變成: random_things=['apple', 'bedroom', 'apple juice', 'dog']

但是我必須這樣做7次,因此我需要能夠將列表分開,例如random_things[1]random things[2] random_things[1] random things[2] etc

我在11年級,所以請盡量保持簡單,因為這是我的第一年編碼

不能完全確定要給用戶的消息應該是您想要的范圍循環和循環他的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列表,您可以使用列表推導

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)]

如果必須使用count變量,則可以使用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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM