简体   繁体   English

如何允许用户在 Python 中使用 while 循环输入列表列表

[英]How to allow a user to input a list of lists in Python with a while loop

Currently I have written code that allows the user to input a list:目前我已经编写了允许用户输入列表的代码:

length=int(input('Please enter how long you want your list: '))
list1=[ ]
p=0
while p<length:
  number=int(input('Please enter an integer: '))
  list1.append(number)
  p=p+1
print(list1)

This allows the user to choose how long they want their list to be, and then chose the integers they want in the list.这允许用户选择他们希望列表的长度,然后在列表中选择他们想要的整数。 The problem with this is that is does not allow the user to enter in nested lists.这样做的问题是不允许用户输入嵌套列表。 Ex.前任。 [2,4,[6,8],10]] I was wondering if here was a way for the user to input a list of list. [2,4,[6,8],10]] 我想知道这里是否是用户输入列表列表的一种方式。 My overall goal is to then flatten that inputed list of list using while loops.我的总体目标是然后使用 while 循环展平输入的列表列表。

A possible solution is this, however it is not very clear what you are trying to do:一个可能的解决方案是这样的,但是还不清楚您要做什么:

running = True
arr = []
while running:
    inp = input("Press enter to input or Q to quit")
    if inp == "":
        while True:
            length=int(input('Please enter how long you want your list: '))
            list1=[]
            p=0
            while p<length:
              number=int(input('Please enter an integer: '))
              list1.append(number)
              p=p+1
            if p == length:
                arr.append(list1)
                break
    elif inp.lower() == "q":
        running = False
print(arr)

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

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