繁体   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