简体   繁体   中英

Python: How to use a list comprehension to replace Nones in one list with values from another list?

a = [0,   -4, 4,    6, 2, 5, 8]
b = [5, None, 3, None, 3, 2, 0]
c = [5,   -4, 3,    6, 3, 2, 0]

I want to take a and b as inputs and get c , ideally using a list comprehension. Obviously I could iterate through this with a loop, but I'm wondering if there is a more elegant/pythonic solution.

this should work:

c = [value if value is not None else a[index] for index, value in enumerate(b)]

You can also use the zip function:

c = [i if j is None else j for i,j in zip(a,b)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM