简体   繁体   English

如何使用列表中的用户输入

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

I have an assignment where I'm asked to to repeat a list but with different "items" (I guess you would call it that). 我有一个作业,要求我重复一个清单,但要使用不同的"items" (我想你会这样称呼)。

the only problem that I seem to have is figuring out how to change the list with user input and how to use something like a counter 我似乎唯一的问题是弄清楚如何通过用户input更改list以及如何使用counter

I'm supposed to change: random_things=['food', 'room', 'drink', 'pet'] 我应该更改: random_things=['food', 'room', 'drink', 'pet']

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

But I have to do this 7 times so I need to be able to keep the lists separate like random_things[1] , random things[2] , etc . 但是我必须这样做7次,因此我需要能够将列表分开,例如random_things[1]random things[2] random_things[1] random things[2] etc

I'm in grade 11 so please try and keep it as simple as you possibly can as this is my first year coding 我在11年级,所以请尽量保持简单,因为这是我的第一年编码

Not fully sure what the message to the user should be what you want is for range loop and to loop over he random_things words: 不能完全确定要给用户的消息应该是您想要的范围循环和循环他的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)

Instead of the temp list you could use a list comprehension : 除了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])

Which could be combined into one single list comprehension: 可以将其合并为一个列表理解:

output = [[input("Choose something related to {}".format(w)) for w in random_things]
          for _ in range(7)]

If you have to use a count variable, you can use while loops: 如果必须使用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

lists indexes start at 0 so the first element is at index 0 not index 1. 列出索引从0开始,所以第一个元素在索引0而不是索引1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM