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

2024-10-01 05:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我目前所掌握的情况:

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?") 

不过,我不知道如何使用这种方法创建无限多个列表。在

如果你有什么问题请问,因为我知道我不善于解释。在


Tags: toyou列表inputcallwhatarelists
2条回答

你在解决XY问题。不需要事先询问list的数量。我建议使用字典:

>>> 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 _ in range(TotalLists):   # The same loop you have now
    ListName = input("whatever...")
    d[ListName] = []

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

相关问题 更多 >