Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple lists in python?

Tags:

python

list

I have 2 lists:

c = [91.0, 92.0, 93.0, 94.0]
a = ['1,2,3,4', '1,2', '4,5,6', '']

result = [911, 912, 913, 914, 921, 922, 934, 935, 936, 94]

I tried this but still unable to get what I exactly want

result = [x for x in zip(c,a)]

Please help me.

like image 999
MHS Avatar asked Sep 18 '26 14:09

MHS


2 Answers

You can do it as follows:

c = [91.0, 92.0, 93.0, 94.0]
a = ['1,2,3,4', '1,2', '4,5,6', '']

c = map(str, map(int, c))

x = [int(c[k]+j) for k,i in enumerate(a) for j in i.split(',')]

>>> print x
[911, 912, 913, 914, 921, 922, 934, 935, 936, 94]
like image 58
sshashank124 Avatar answered Sep 20 '26 04:09

sshashank124


I tried to keep it readable:

C = [91.0, 92.0, 93.0, 94.0]
A = ['1,2,3,4', '1,2', '4,5,6', '']

result = []
for c, a in zip(C,A):
  str_c = str(int(c))
  nums = a.split(',')
  for num in nums:
    result.append(int(str_c + num))


print(result)
like image 45
Jasper Avatar answered Sep 20 '26 02:09

Jasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!