0

I have three arrays:

arr1 = ['name1', 'name2', ...]
arr2 = ['192.168.1.1', '192.168.1.2', ...]
arr3 = ['port1', 'port2', ...]

I would like to merge them in one like this:

final_arr = ['name1', '192.168.1.1', 'port1', 'name2', '192.168.1.2', 'port2', ...]

I tried with dict.fromkeys() but doesn't seem to be the answer ...

If you had any idea?

Thanks!!

2 Answers2

1

I would try something like this:

arr1 = ['name1', 'name2']
arr2 = ['192.168.1.1', '192.168.1.2']
arr3 = ['port1', 'port2']

arr = [y for x in zip(arr1, arr2, arr3) for y in x]
# ['name1', '192.168.1.1', 'port1', 'name2', '192.168.1.2', 'port2']
norok2
  • 25,683
  • 4
  • 73
  • 99
  • This solution returns something like this: `['name1', '192.168.1.1', 'port1', 'name2', '192.168.1.2', 'port2']` ... Just what I was expecting ... THANKS!! – Gueug78400 Nov 03 '20 at 14:27
0

If you have the same length for the three array you can just make a for loop like that :

arr1 = ['name1', 'name2']
arr2 = ['192.168.1.1', '192.168.1.2']
arr3 = ['port1', 'port2']
arr = []

for i in range(0, len(arr1)):
  arr.extend([arr1[i], arr2[i], arr3[i]])

print(arr)
lascapi
  • 51
  • 6