AnarKi
AnarKi

Reputation: 997

Join elements of an arbitrary number of lists into one list of strings python

I want to join the elements of two lists into one list and add some characters, like so:

list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']

joined_list = ['some1_thing1', 'some2_thing2', 'some3_thing3']

however i don't know in advance how many lists I will have to do this for, i.e. I want to do this for an arbitrary number of lists

Also, I currently receive a list in the following form:

list_A = [('some1','thing1'),('some2','thing2'),('some3','thing3')]

so I split it up into lists like so:

list_B = [i for i in zip(*list_A)]

I do this because sometimes I have an int instead of a string

list_A = [('some1','thing1',32),('some1','thing1',42),('some2','thing3', 52)] 

so I can do this after

list_C = [list(map(str,list_B[i])) for i in range(0,len(list_B)]

and basically list_1 and list_2 are the elements of list_C.

So is there a more efficient way to do all this ?

Upvotes: 1

Views: 190

Answers (3)

akshat
akshat

Reputation: 1217

You can join function like this on the base list_A, itself, no need to split it for probable int values:

list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)] 
["_".join(map(str, i)) for i in list_A]

Output:

['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52']

Update:

For you requirement, where you want to ignore last element for last tuple in your list_A, need to add if-else condition inside the list-comprehension as below:

["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A  ]

Updated Output:

['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']

Upvotes: 2

AnarKi
AnarKi

Reputation: 997

For ignoring the last element of every tuple in list_A, I found this to be the quickest way:

["_".join(map(str, i)) for i in [x[:-1] for x in list_A] ]

Upvotes: 1

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

Try this if you are using python>=3.6:

[f'{i}_{j}' for i,j in zip(list_1, list_2)]

If you using python3.5, you can do this:

 ['{}_{}'.format(i,j) for i,j in zip(list_1, list_2)]

also you can use this if you don't want to use formatted string:

['_'.join([i,j]) for i,j in zip(list_1, list_2)]

Upvotes: 3

Related Questions