【问题标题】:Print some of list by for in python在 python 中通过 for 打印一些列表
【发布时间】:2022-11-24 18:06:18
【问题描述】:

我有 4 个列表,我想打印它们,但它返回列表的名称。

list1 = ["a", "b", "c", "d"]
list2 = ["a", "b", "c"]
list3 = ["a", "b"]
list4 = ["a"]

for i in range(1,5):
    print(list[i])

表明:

list[1]
list[2]
list[3]
list[4]

我需要,例如 list1 的 ["a", "b", "c", "d"]

【问题讨论】:

  • 不是那样的,您需要对变量的工作原理有基本的了解,因为您的解决方案 print(globals()[f'list{i}']) 会起作用,但这不是您想要做的

标签: python list for-loop


【解决方案1】:

如果你想像你正在尝试的那样打印它们,你可以制作一个列表列表:

list1 = [
    ["a", "b", "c", "d"],
    ["a", "b", "c"],
    ["a", "b"],
    ["a"]
]

for i in range(len(list1)):
    print(list1[i])

【讨论】:

    【解决方案2】:

    变量不是那样工作的。如果您需要类似的方法,可以使用字典。

    dict_ = {
        "list1" : ["a", "b", "c", "d"],
        "list2" : ["a", "b", "c"],
        "list3" : ["a", "b"],
        "list4" : ["a"],
    }
    
    for i in range(1, 5):
        print(dict_["list"+str(i)])
    

    【讨论】:

      【解决方案3】:

      如果你想循环打印它们,你需要先把它们放在一个“容器”中(容器注意到它自己的列表)。

      list1 = ["a", "b", "c", "d"]
      list2 = ["a", "b", "c"]
      list3 = ["a", "b"]
      list4 = ["a"]
      
      container = [list1, list2, list3, list4]
      for list in container:
          print(list)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        • 2018-02-15
        • 2021-08-05
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        相关资源
        最近更新 更多