Combining Lists in python with common elements -
i generating lists '1' , '0' in them:
list_1 = [1,0,0,1,0,0] list_2 = [1,0,1,0,1,0]
i trying combine them if '1' appears in either list, appears in new list, , replaces '0'
new_list = [1,0,1,1,1,0]
what code be?
use bitwise or |
on list comprehension , using zip
function:
>>> [x | y x,y in zip(list_1, list_2)] [1, 0, 1, 1, 1, 0]
if lists don't have same length, use zip_longest
itertools
module:
>>> l1 = [1,1,1,0,0,1] >>> l2 = [1,0,1,1,1,0,0,0,1] >>> >>> [x | y x,y in zip_longest(l1, l2, fillvalue=0)] [1, 1, 1, 1, 1, 1, 0, 0, 1]
another way, use starmap
, remember in python3, yields generator have convert list
after that, way:
>>> itertools import starmap >>> operator import or_ #bitwise or function passed starmap >>> list(starmap(or_, zip_longest(l1,l2, fillvalue=0))) [1, 1, 1, 1, 1, 1, 0, 0, 1]
Comments
Post a Comment