How to combine list of lists with list of strings

Viewed 78

I have a list below

a = [['1321.', 'Fuji', 'Kto', '776'], ['3123.', 'dake', 'Cu', '392'], ['123.', 'Hota', 'Cu', '310']]

And I have two lists of strings and want to append them into the list above by sequence to form a new list.

id = ['pid=1882','pid=1086','pid=180']

lgt = ['38.72347',
 '38.23833',
 '37.64986']

The result should become

new_list = [['1321.', 'Fuji', 'Kto', '776', 'pid=1882', '38.72347'], 
['3123.', 'dake', 'Cu', '392', 'pid=1086', '38.23833'], 
['123.', 'Hota', 'Cu', '310', 'pid=180', '37.64986']]

I have tried the zip method but the output is a tuple not a list.

new_list = list(zip(a, id, lgt))

new_list -> [[['1321.', 'Fuji', 'Kto', '776'], 'pid=1882', '38.72347'], 
[['3123.', 'dake', 'Cu', '392'], 'pid=1086', '38.23833'], 
[['123.', 'Hota', 'Cu', '310'], 'pid=180', '37.64986']]]

Thanks!

4 Answers

You can use zip, but you need to unpack the list element afterwards.

a = [['1321.', 'Fuji', 'Kto', '776'], ['3123.', 'dake', 'Cu', '392'], ['123.', 'Hota', 'Cu', '310']]
ids = ['pid=1882', 'pid=1086', 'pid=180']
lgt = ['38.72347', '38.23833', '37.64986']

result = [[*x, y, z] for x, y, z in zip(a, ids, lgt)]
print(result)
# [['1321.', 'Fuji', 'Kto', '776', 'pid=1882', '38.72347'], ['3123.', 'dake', 'Cu', '392', 'pid=1086', '38.23833'], ['123.', 'Hota', 'Cu', '310', 'pid=180', '37.64986']]

With the tuples generated from zipping the three lists, you can use iterator unpacking to assign items from ids and lgt into a list to concatenate with the list items from a:

[s + r for s, *r in zip(a, ids, lgt)]

This returns:

[['1321.', 'Fuji', 'Kto', '776', 'pid=1882', '38.72347'],
 ['3123.', 'dake', 'Cu', '392', 'pid=1086', '38.23833'],
 ['123.', 'Hota', 'Cu', '310', 'pid=180', '37.64986']]

Check this out :

list = [['1321.', 'Fuji', 'Kto', '776'], ['3123.', 'dake', 'Cu', '392'], ['123.', 'Hota', 'Cu', '310']]
id = ['pid=1882','pid=1086','pid=180']
lgt = ['38.72347','38.23833','37.64986']

for index, value in enumerate(list):
    list[index].append(id[index])
    list[index].append(lgt[index])

You can use the following solution:

list(zip(*zip(*a), id, lgt))

Result:

[('1321.', 'Fuji', 'Kto', '776', 'pid=1882', '38.72347'),
 ('3123.', 'dake', 'Cu', '392', 'pid=1086', '38.23833'),
 ('123.', 'Hota', 'Cu', '310', 'pid=180', '37.64986')]

If you need a list of lists:

list(map(list, zip(*zip(*a), id, lgt)))
Related