How to iterate through a list of lists in python?

前端 未结 7 1958
陌清茗
陌清茗 2020-12-09 11:27

I have a list of lists like this.

documents = [[\'Human machine interface for lab abc computer applications\',\'4\'],
             [\'A survey of user opinio         


        
相关标签:
7条回答
  • 2020-12-09 12:15

    The simplest solution for doing exactly what you specified is:

    documents = [sub_list[0] for sub_list in documents]
    

    This is basically equivalent to the iterative version:

    temp = []
    for sub_list in documents:
        temp.append(sub_list[0])
    documents = temp
    

    This is however not really a general way of iterating through a multidimensional list with an arbitrary number of dimensions, since nested list comprehensions / nested for loops can get ugly; however you should be safe doing it for 2 or 3-d lists.

    If you do decide to you need to flatten more than 3 dimensions, I'd recommend implementing a recursive traversal function which flattens all non-flat layers.

    0 讨论(0)
提交回复
热议问题