【问题标题】:Python Looping through a group of lists [duplicate]Python循环遍历一组列表[重复]
【发布时间】:2019-06-15 01:06:44
【问题描述】:

是否可以循环选择列表名称?

例如:

list_A=[12,3,6]
list_B=[3,42,6]
list_C=[44,33]


for i in list_A:
     i=i*4

但我不想多次这样做,而是想在此基础上做一个列表:

to_loop = [list_A,list_B,list_C]

for l in to_loop:
     for i in list_A:
           i=i*4

【问题讨论】:

  • 您确实可以遍历列表列表。你的意思是你也想遍历它们的元素吗?
  • 看你想要什么,但是这个问题已经被问过很多次了,你发帖前有没有先搜索?
  • 是的,我将遍历列表中的元素。
  • 您希望i 在该循环的第一次迭代中出现什么? 1,或[1],或'list_A'
  • 我只是想避免多次编写循环,所以希望我可以在嵌套循环中完成所有操作

标签: python loops


【解决方案1】:

我不完全确定你在这里问什么,但如果你想循环遍历每个列表中的项目作为一个整体,它相当简单,只需循环两次。

    list_A=[1]
    list_B=[3,42,6]
    list_C=[44,33]

    to_loop = [list_A,list_B,list_C]

    for l in to_loop:
          for i in l:

【讨论】:

    【解决方案2】:

    使用字典!

    to_loop = {"list_A":[1], "list_B":[3,42,6], "list_C":[44,33]}
    
    for l in to_loop:
          print(l)          #Will print the name of the list
          print(to_loop[l]) #Will print the list itself
    

    【讨论】:

      【解决方案3】:

      我怀疑(你可能已经测试过了)。但是,您可以将其设为二维数组(未经测试):

      arrayNumbers= [ [1], [3, 42, 6], [44, 33] ]
      
      for l in arrayNumbers:
            do something(l)
      

      首先使用 [1] 调用某些东西,然后使用 [3, 42, 6],然后使用 [44, 33] 在里面你可以进一步循环这些子列表。

      【讨论】:

        【解决方案4】:
        list_A=[1]
        list_B=[3,42,6]
        list_C=[44,33]
        
        to_loop = [list_A,list_B,list_C]
        
        for l in to_loop:
            for x in l:
                print x
        
        • 上面的代码将打印每个列表中的每个元素
        • to_loop = [list_A, list_B, list_C] 表示列表列表,而不是列表名称列表。

        输出:

        1
        3
        42
        6
        44
        33
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-26
          • 2019-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-26
          • 1970-01-01
          相关资源
          最近更新 更多