-1

I've got something like:

list1 = [1, 3, None]
list2 = [2, 5, None]

And I'm looking to get something like:

merged_list = [12, 35, None]

P.S. Both lists will always have the same length and could have a None value as an element.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lucas Mengual
  • 263
  • 6
  • 21
  • Possible duplicate of [Element-wise addition of 2 lists?](https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists) – Mayeul sgc Oct 14 '19 at 14:53
  • What have you tried, and what exactly is the problem with it? – jonrsharpe Oct 14 '19 at 14:54
  • i think you should explain why you want to do this – incapaz Oct 14 '19 at 15:05
  • @incapaz @jonsharpe @mayeul-sgc Hi, sorry for maybe not explaining that well the output, but essentially is merging the elements of both in the subsequential order (i.e. if the element of first list is `'lala'`, and from second list is `'land'`, the first element of the `merged_list` would be `'lalaland'`, just that in this case is numerical values. – Lucas Mengual Oct 14 '19 at 15:10

2 Answers2

1

You can zip together the two lists and process each respective pair of elements.

[10 * a + b if a and b else None for a, b in zip(x, y)]

This list comprehension will combine a and b if neither are None. Otherwise, it will just put None.

Edit: If you just want to merge whatever values, do the same thing, but make sure you cast to a string so any value will work:

[str(a) + str(b) if a and b else None for a, b in zip(x, y)]

Note, it doesn't do the merge in place, but returns a new array with the combined values

Jtcruthers
  • 854
  • 1
  • 6
  • 23
  • 1
    or [10*a + b if a and b else None for a,b in zip(list1, list2)] – mauve Oct 14 '19 at 14:58
  • @mauve Good idea, I changed it. That's a better solution since they want the elements to be ints instead. No casts needed – Jtcruthers Oct 14 '19 at 15:03
  • Thanks for the quick answer, but sorry i didnt explain well. But essentially is merging the elements of both in the subsequential order (i.e. if the element of first list is `'lala'`, and from second list is `'land'`, the first element of the `merged_list` would be `'lalaland'`, just that in this case is numerical values. – Lucas Mengual Oct 14 '19 at 15:16
  • 1
    @LucasMengual Changed it to work with strings or ints. The logic is the same, just how you handle the combining of the two values. – Jtcruthers Oct 14 '19 at 15:18
0

You probably want to combine strings here. Something like

merged_list = []
for(i,j in zip(list1, list2):
  if(element is not None):
    merged_list.append(float(str(i) + str(j))
  else:
    merged_list.append(None)

Code not tested!

Jacob N
  • 76
  • 7