Python 将用户输入转换为列表名

Python 将用户输入转换为列表名,python,list,dictionary,Python,List,Dictionary,以下是我到目前为止的情况: TotalLists=int(input("How many Lists are you making?")) TotalListsBackup=TotalLists Lists=[] while TotalLists>0: ListName=input("What would you like to call List Number "+str(TotalLists)) Lists.append(ListName) TotalLists=Tota

以下是我到目前为止的情况:

TotalLists=int(input("How many Lists are you making?"))
TotalListsBackup=TotalLists
Lists=[]

while TotalLists>0:
  ListName=input("What would you like to call List Number "+str(TotalLists))
  Lists.append(ListName)
  TotalLists=TotalLists-1

TotalLists=TotalListsBackup-1

while TotalLists>=0:
  Lists[TotalLists] #I would like to create actual lists out of the list names at this step but I dont know how...
  TotalLists=TotalLists-1

TotalLists=TotalListsBackup-1

print("Here are your Lists: ")

while TotalLists>=0:
  print(Lists[TotalLists])
  TotalLists=TotalLists-1
我希望能够:

  • 从列表名称中创建一个列表
  • 代码允许用户在没有上限的情况下创建任意多的列表
例如,我想输入:杂货店, 代码将创建一个名为“杂货店”的列表


我想到的解决办法是:

  • 阵列?(我从未使用过它们,我对Python编程非常陌生,知道的也不多)

  • 名单?(不知道怎么做。查了一下,但没有得到直接的答案)

  • 使用变量,创建名称如下的列表:

    List1[]
    
并称之为:

    List1Name=input("What would you like to call list 1?") 
我不知道如何用这种方式创建无限多的列表


如果您有任何问题,请提问,因为我知道我不擅长解释。

您正在解决XY问题。无需提前询问
列表的编号。我建议使用字典:

>>> lists = {}
>>> while 1:
...     newlist = input("Name of new list (leave blank to stop)? ")
...     if newlist:
...             lists[newlist] = []
...             while 1:
...                     newitem = input("Next item? ")
...                     if newitem:
...                             lists[newlist].append(newitem)
...                     else:
...                             break
...     else:
...             break
...
Name of new list (leave blank to stop)? groceries
Next item? apples
Next item? bananas
Next item?
Name of new list (leave blank to stop)? books
Next item? the bible
Next item? harry potter
Next item?
Name of new list (leave blank to stop)?
>>> lists
{'groceries': ['apples', 'bananas'], 'books': ['the bible', 'harry potter']}

有趣的是,你已经将问题标记为“字典”,但在你的帖子中没有提到这一点。有人叫你用字典吗?这正是您应该做的,就像这样(假设Totalists已经定义):


最后是一个字典d,其中包含用户输入的名称键和空列表值。词典条目的数量为。我忽略了用户输入相同名称两次的可能性。

完美!不过,只有一个问题,有没有一种方法可以让用户输入另一个密钥。这样,我可以使用for循环以更好的方式将它们全部打印出来,例如:---索引中的名称:打印(名称)索引中的项目[]:打印(项目)----但这不起作用,我不确定另一个键是什么。当然,您可以使用第二个词典,将用户输入的名称与您选择的其他对象关联起来。您还可以对键列表进行排序(使用内置的
sorted
函数)并循环使用,以生成格式良好、按字母顺序排列的打印输出。
d = {}

for _ in range(TotalLists):   # The same loop you have now
    ListName = input("whatever...")
    d[ListName] = []