LucSpan LucSpan - 9 months ago 32
Python Question

Python: merge two ordered lists, replacing elements conditionally

Beginner's question.

I have two ordered lists with the same order,

list_1=['de', 'de', 'de', '3']
list_2=['6', '5', '3', 'not']

so the n-th element of list_1 corresponds to the n-th element of list_2.

I want to merge the two lists while perserving their order. Moreover, the list resulting from the merge should consist entirely out of numbers, i.e.

merged_list=['6', '5', '3', '3']

Preferably, I merge by position in the list conditionally on string or numeric values. I have the same issue with other ordered lists, but with those lists I want to replace numeric values with string values. I.a. to solve my troubles with all the ordered lists I have I'd like to do something like:

replace element_n of list_i with element_n of list_j if element_n of list_i equals 'z'

where z is either a numeric value or a string value, dependent on the nature of the list.

Answer Source

You can use zip to aggregates two list items:

>>> list_1 = ['de', 'de', 'de', '3']
>>> list_2 = ['6', '5', '3', 'not']
>>> zip(list_1, list_2)
<zip object at 0x1029e53c8>
>>> list(zip(list_1, list_2))
[('de', '6'), ('de', '5'), ('de', '3'), ('3', 'not')]

, and str.isdigit to check if the given string is a number:

>>> '123'.isdigit()
>>> 'de'.isdigit()

By combining with conditional expression and list comprehension, you will get what you want:

>>> [a if a.isdigit() else b for a, b in zip(list_1, list_2)]
['6', '5', '3', '3']