Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to join the first 2 elements from each list in a list of lists

I have this list of lists:

listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

^^ That was just a example, I will have many more lists in my list of lists with the same format. This will be my desired output:

listoflist = [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

Basically in each list I want to join first index with the second to form a full name in one index like in the example. And I would need a function for that who will take a input a list, how can I do this in a simple way? (I don't want extra lib for this). I use python 3.5, thank you so much for your time!

like image 685
Tatu Bogdan Avatar asked Dec 24 '22 14:12

Tatu Bogdan


2 Answers

You can iterate through the outer list and then join the slice of the first two items:

def merge_names(lst):
   for l in lst:
      l[0:2] = [' '.join(l[0:2])]

merge_names(listoflist)
print(listoflist)
# [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]
like image 143
Moses Koledoye Avatar answered Apr 27 '23 01:04

Moses Koledoye


this simple list-comprehension should do the trick:

res = [[' '.join(item[0:2]), *item[2:]] for item in listoflist]

join the first two items in the list and append the rest as is.

like image 36
hiro protagonist Avatar answered Apr 27 '23 00:04

hiro protagonist