Function for combining the first two items from each list in a list of lists

I have a list of lists:

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

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

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

Basically in each list, I want to join the first index with the second in order to form the full name in one index, as in the example. And I need a function for whoever takes the input list, how can I do this in a simple way? (I do not need extra lib for this). I am using python 3.5, thank you so much for your time!

+4
source share
4 answers

, :

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']]
+6

:

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

join .

+2

You can try the following:

f = lambda *args: [' '.join(args[:2]), *args[2:]]

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

final_list = [f(*i) for i in listoflist]

Conclusion:

[['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]
+1
source

You can also use list comprehension:

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

def f(lol):
  return [[' '.join(l[0:2])]+l[3:] for l in lol]

listoflist = f(listoflist)
print(listoflist)
# => [['BOTOS AUGUSTIN', 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 'February 2015', 600, 'ALOCATIA']]
+1
source

Source: https://habr.com/ru/post/1685255/


All Articles