Stark
Stark

Reputation: 197

How to concatenate the list elements

Here I'm having the list of list, i want to concatenate only the first two elements if the second element of list has name. else do nothing.

The below is the code which i tried:

lst_1 = [['ANTWERP' 'BRIDGE', '05', 'N'], 
         ['NORTHERN' 'VIGOUR', '05', 'N'],
         ['BRIDGE', '98', 'N']]
for i in lst_1:
    for j in i:               
        j[0:2] = ['_'.join(j[0:2])]

expected output:

[['ANTWERP_BRIDGE', '05', 'N'], 
 ['NORTHERN_VIGOUR', '05', 'N'],
 ['BRIDGE', '98', 'N']]

can i find any way to do this?

Upvotes: 3

Views: 492

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114548

First you need to decide what it means for the second element to be a name. I suggest two possibilities. One is to check the length of the sub-list:

if len(i) == 4:

Another is to check for integers:

if len(i) > 2 and not i[1].isdigit():

In either case, you can merge pretty much as you did before, but with an if instead of the inner for loop:

for i in lst_1:
    if <condition>:
        i[:2] = ['_'.join(i[:2])]

This modifies lst_1 in-place. If you want to replace it with a new object, use @Sayse's answer.

Upvotes: 4

Sayse
Sayse

Reputation: 43330

I wouldn't over think it, simply just concatenate the elements then add on the rest

 [[f"{i[0]}_{i[1]}" if len(i) == 4 else i[0], *i[-2:]] for i in lst_1]

Upvotes: 5

Related Questions