每次输入新值时如何将元素添加到下一个列表?

时间:2014-11-14 16:53:36

标签: list nested

例如我有一个包含月份和月份数的列表,我想在每次输入时添加[0] [1],[1] [1],[2] [1]中的其他值新的价值。我正在考虑追加功能,但我不确定如何重新编码以使该值输入到列表中的下一个列表中。

list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]

def month():
    global list
    count = 0
    while value_count < 3:
        value = int(input("Enter a value: "))
        if value in range(101):
            list[0][1].append(value)
            count += 1
        else:
            print('Try Again.')
month()

我希望得到类似的结果:

list = [[['Jan'],1,54], [['Feb'],2,65],[['Mar'],3,62]]

其中54,65和62是用户输入的随机数。

1 个答案:

答案 0 :(得分:0)

请参阅代码中的注释

# list is a function used by python to create lists,
# do not use builtins' names for your variables
my_list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]

def month():
    # print("Don't use globals!\n"*100)
    # you can pass arguments to a function, like in "def mont(my_list)"
    global my_list

    # cycling on a numerical index is complicated, use this syntax
    # instead, meaning "use, in turn, the same name to refer to each
    # element of the list" 
    for element in my_list:
        value = int(input("Enter a value: "))
        # if value in range(101):
        if 1: # always true, the test doesn't work as you expect
            element.append(value)
        else:
            print('Try Again.')
month()
print my_list

你可以像这样编写输入循环

        value = 101
        while not (0<=value<101):
            value = int(input(...)
        element.append(value)

这样你就会错过替代提示,但它已经足够好了。