Grouping lists within lists in Python 3

前端 未结 3 1237
不知归路
不知归路 2021-01-27 05:32

I have a list of lists of strings like so:

List1 = [
          [\'John\', \'Doe\'], 
          [\'1\',\'2\',\'3\'], 
          [\'Henry\', \'Doe\'], 
          [         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 05:50

    This should do what you want assuming you always want to take pairs of the inner lists together.

    list1 = [['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6']] 
    output = [list(pair) for pair in zip(list1[::2], list1[1::2])]
    

    It uses zip, which gives you tuples, but if you need it exactly as you've shown, in lists, the outer list comprehension does that.

提交回复
热议问题