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

时间:2016-04-02 15:50:42

标签: python list python-3.x input

我有一个作业,我被要求重复一个列表,但使用不同的Item **queue; (我想你会称之为)。

我似乎唯一的问题是弄清楚如何更改"items"与用户list以及如何使用类似input

的内容

我应该改变: counter

成: random_things=['food', 'room', 'drink', 'pet']

但我必须random_things=['apple', 'bedroom', 'apple juice', 'dog']次执行此操作,因此我需要能够将列表分开,例如7random_things[1]random things[2]

我在11年级,所以请尽量保持简单,因为这是我的第一年编码

1 个答案:

答案 0 :(得分: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)

您可以使用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])

可以合并为一个列表理解:

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。

相关问题