Enumerate list of elements starting from the second element

前端 未结 3 550
不知归路
不知归路 2021-01-21 13:46

I have this list

[[\'a\', \'a\', \'a\', \'a\'],
 [\'b\', \'b\', \'b\', \'b\', \'b\'],
 [\'c\', \'c\', \'c\', \'c\', \'c\']]

and I want to conca

3条回答
  •  有刺的猬
    2021-01-21 14:26

    There is not much merit here for using enumerate() ... you can simply .pop() the n-th item from inner lists. For loop over your data, starting at index 1 and add the 2nd value (popped) to the 1st element of the inner list:

    data = [['a', 'a', 'a', 'a'],
     ['b', 'b', 'b', 'b', 'b'],
     ['c', 'c', 'c', 'c', 'c']] 
    
    for row in range(1,len(data)):  # apply to 1st to n-th inner list by index
        item = data[row].pop(2)         # remove the 2nd item from inner list
        data[row][1] += item            # add it to the 1st of inner list
    
    print(data)
    

    Output:

    [['a', 'a', 'a', 'a'], 
     ['b', 'bb', 'b', 'b'], 
     ['c', 'cc', 'c', 'c']]
    

    See list.pop(index)

提交回复
热议问题