简体   繁体   中英

Appending elements into nested lists with 12 user inputs

I want to append 12 inputs from the user into the lists, for example for each month, I want the user to input a value. However I want to make it so that the loop adds the value to the next according list everytime the loop reloops. I am also limited to down on what I can use for my assignment. Below is what I have so far in my coding.

value_store = [[['Jan']],[['Feb']],[['Mar']],[['Apr']],[['May']],[['Jun']],[['Jul']],[['Aug']],[['Sep']],[['Oct']],[['Nov']],[['Dec']]]

def get_value():
    count = 0
    while count < 12:
        value = float(input('Enter a value between 0 and 2000: '))
        if value in range(2001):
              for k in value_store[:1]:
                    value_store[0].append(round(value,3))
                    count += 1
        else:
            print('Enter new value')
        print(value_store)
get_value()

The coding above does it to one of the lists and it's looped 12 times. The result I want from the list is:

value_store = [[['Jan'],45],[['Feb'],54],[['Mar'],78],[['Apr'],97],[['May'],82],[['Jun'],74],[['Jul'],23],[['Aug'],23],[['Sep'],34],[['Oct'],54],[['Nov',12]],[['Dec'],120]]

The above values are values that the user has entered when the loop loops around 12 times. I want the values to be inserted into each of the lists in that format, however I'm confused with how I can change the code to do that.

Just some annotations to your code:

if value in range(101):

you should check 0<= value <= 100. Otherwise you will make a list for every input an check if the value is in the list (for which the whole list must be searched). You ask for numbers between 0 and 300 and check for 100.

for k in range(value_store[:1]):

you iterate over the first element and the adress it by the index 0:

value_store[0].append(round(value,3))

so there is no need for iterating.

Here is a working example:

value_store = [[['Jan']],[['Feb']],[['Mar']],[['Apr']],[['May']],[['Jun']],[['Jul']], [['Aug']],[['Sep']],[['Oct']],[['Nov']],[['Dec']]]

def get_value():
    global value_store
    for value_list in value_store:
        month = value_list[0][0]
        value = -1
        while not 0 <= value <= 100:
            value = float(input('Enter a value between 0 and 300 for {0}: '.format(month)))
        value_list.append(round(value, 3))
    print(value_store)
get_value()

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