简体   繁体   中英

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

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

I'm supposed to change: random_things=['food', 'room', 'drink', 'pet']

into: 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 .

I'm in grade 11 so please try and keep it as simple as you possibly can as this is my first year coding

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=['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 :

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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