简体   繁体   中英

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!

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

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.

You can try this:

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]

Output:

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

You can use a list comprehension as well:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM