首页 > 解决方案 > Python,FOR 循环 - 创建列表

问题描述

这是我创建列表的代码,但它是如此残酷和不优雅,你们有什么想法让它更流畅吗?

问题是,我想编写代码,您可以在其中创建自己的列表,选择要创建的列表数量以及每个项目应该有多少项目 - 不使用 while 循环。我可以通过在 for 循环 (number_of_lists) 中输入范围来管理创建一定数量的列表

    i = 0
    number_of_lists = input('How many lists you want to make?  >')

    for cycle in range(number_of_lists):   #this was originaly range(3), 
        item1 = raw_input('1. item > ')    #and will only work now pro-
        item2 = raw_input('2. item > ')    #perly, if n_o_l is exact. 3
        item3 = raw_input('3. item > ') 



                                           #everything is wrong with this
        print "-------------------"        #code, i need it much more au-
                                           #tonomous, than it is now.
        if i == 0:
            list1 = [item1, item2, item3]
        if i == 1:
            list2 = [item1, item2, item3]
        if i == 2:
            list3 = [item1, item2, item3]
        i += 1  


    print list1
    print list2
    print list3

事情是我也想避免所有“如果我 == int”的事情。

现在它只会创建 3 个列表,对,因为我最初使用整数 3 而不是 number_of_lists 来创建 3 个列表。

现在你看到了我希望的问题。如果可能,我需要从输入创建新列表并命名它们,因此我可以将它命名为 DOGS 或 w/e 而不是 list1。

我需要它更简单和相互关联,我希望你理解我的问题,也许有一些顺利的解决方案,谢谢:)

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 好的,我想我现在明白了 - 这是新版本,几乎可以做我想做的事情:

    number_of_lists = input('How many lists you want to make?  >')

    allItems = []


    for cycle in range(int(number_of_lists)):
         items = []
         number_of_items = input('How much items in this list?  >')

         for i in range(int(number_of_items)):
                 item = raw_input(str(i+1) + ". item > ")
                 items.append(item)

         allItems.append(items)

         print("-------------------")


    print allItems

如果有人知道如何使它更有效和更清晰,请在这里告诉我!:) 感谢您的帮助

标签: listloops

解决方案


您可以将您的列表添加到另一个列表中,这样它就像您想要的那样动态。下面的例子:

number_of_lists = input('How many lists you want to make?  >')

allItems = []
for cycle in range(int(number_of_lists)):
    items = []
    for i in range(1, 4):
        item = input(str(i) + ".item > ")
        items.append(item)

    allItems.append(items)

    print("-------------------")


for items in allItems:
  for item in items:
    print(item)

  print("-------------")

在将number_of_listsint解析为int. 如果用户输入一个字母,它会抛出一个错误。


推荐阅读