0

I'm trying to concatenate a list with a nested list, but without using dictionary because the dictionary is not keeping the same order and this is screwing a bit what I'm doing. Not sure if this is possible, but basically what I have is:

list1=['a','b','c','d','e']
list2=[['1','2','3'],['4','5','6'],['7','8','9'],['T1','T2','T3'],[]]

and the output I need is:

[['a_1','a_2','a_3'],['b_4','b_5','b_6'],['c_7','c_8','c_9'],['d_T1','d_T2','d_T3'],['e']]

I'm able to do it with a dictionary with this code:

dict = dict(zip(list1, list2))
for key,values in dict.iteritems():
    vals = dict[key]
    values = [key + '_' + str(v) for v in vals]
    test.append(values)

but the order is not the same, and I need to match some lists together later... So I really would prefer to avoid the dictionary part, anyone having any idea?

Thanks!

1 Answer 1

2

you were almost there:

test = []
for key, values in zip(list1, list2):
    if values:
        values = [key + "_" + str(v) for v in values]
        test.append(values)
    else:
        test.append([key])
print(test)

just iterate over the pairs from zip; if you pack that in a dict first it will mess up the order in python 2 (in python >= 3.4 you are fine!).

you could also pack all that directly in a list comprehension (and maybe use string formatting):

test = [
    ["{}_{}".format(key, v) for v in values] if values else [key]
    for key, values in zip(list1, list2)
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.