简体   繁体   English

使用12个用户输入将元素追加到嵌套列表中

[英]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. 我想将用户的12个输入追加到列表中,例如,对于每个月,我希望用户输入一个值。 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. 上面的编码将其执行到列表之一,并循环了12次。 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. 上面的值是当循环大约循环12次时用户输入的值。 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). 您应该检查0 <= value <=100。否则,将为每个输入创建一个列表,检查该值是否在列表中(必须搜索整个列表)。 You ask for numbers between 0 and 300 and check for 100. 您要求输入0到300之间的数字,并检查100。

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

you iterate over the first element and the adress it by the index 0: 您遍历第一个元素并按索引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()

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

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