How to concatenate the elements of a list fixing two pivots?

I have a large nested list with lots of elements in their respective sub-lists. The list looks like this:

[
 ['Pack', 'my', 'box', 'with', 'five', 'dozen', 'liquor', 'jugs'],
 ['The', 'five', 'boxing', 'wizards', 'jump', 'quickly']
]

How can I join the middle elements of the list with a "separator", ignoring the first and the last element of any list size efficiently? For instance:

[
 ['Pack', 'my_box_with_five_dozen_liquor', 'jugs'],
 ['The', 'five_boxing_wizards_jump', 'quickly']
]

I tried:

lst = []

for i in l:
    p1 = i[0]
    p2 = i[-1]
    my_list = i[1:-1]
    new = '_'.join(my_list)
lst.append(new)
lst.insert(0, p1)
lst.insert(len(lst), p2)

Although it is working, I think this is not very pythonic and might not work for large lists. Is there any other way to get the above output?

4 answers

  • answered 2019-08-13 03:37 mamun

    a = [
         ['Pack', 'my', 'box', 'with', 'five', 'dozen', 'liquor', 'jugs'],
         ['The', 'five', 'boxing', 'wizards', 'jump', 'quickly']
        ]
    b = []
    for aa in a:
        b += [[aa[0], '_'.join(aa[1:-1]), aa[-1]]]
    
    print(b)
    #prints [['Pack', 'my_box_with_five_dozen_liquor', 'jugs'],
    #        ['The', 'five_boxing_wizards_jump', 'quickly']]
    

  • answered 2019-08-13 03:38 RootTwo

    for row in lst:
        row[1:-1] = ['_'.join(row[1:-1])]
    

  • answered 2019-08-13 03:38 Austin

    You can use a list-comprehension:

    [[x[0], '_'.join(x[1:-1]), x[-1]] for x in lst]
    

    where lst is your list of lists.

    Example:

    lst = [
     ['Pack', 'my', 'box', 'with', 'five', 'dozen', 'liquor', 'jugs'],
     ['The', 'five', 'boxing', 'wizards', 'jump', 'quickly']
    ]
    
    print([[x[0], '_'.join(x[1:-1]), x[-1]] for x in lst])
    # [['Pack', 'my_box_with_five_dozen_liquor', 'jugs'], ['The', 'five_boxing_wizards_jump', 'quickly']]
    

  • answered 2019-08-13 03:41 binbeing

    would you like to list comprehension

    [[i[0], "_".join(i[1:-1]), i[-1]] for i in l ]