比较两个列表,并将列表一中的值替换为列表2中的值

时间:2018-11-23 00:15:08

标签: python

我有两个列表。

a = [1,2,3,4,0,4,5,6,3,6,0,5,6,8,0,3]
b = [1,2, None,4,5,4,5,6,3,6,7,5,6,8,4, None]

我想要一个这样的结果列表。

new_list = [1,2,3,4,5,4,5,6,3,6,7,5,6,8,4,3]

列表b仅替换列表a中的0,并且未触及其他元素,例如未替换None。

我该如何做呢? 提前致谢。请让我知道是否需要其他信息。

我尝试了以下方法,但它不起作用。

_ = dict(zip(a,b))
for k,v in _.items():
   if k == 0:
       a = a.replace(k,v)

4 个答案:

答案 0 :(得分:3)

您可以使用zip和一个简单的列表推导通过选择a的元素(如果不为0)或b的元素(如果对应的{{1 }}元素为零:

a

答案 1 :(得分:0)

out = []
for ea, eb in zip(a, b): 
  res = ea 
  # if element in a is 0 and corresponding element in b is not None
  if ea == 0 and eb:
    res = eb 
  out.append(res)

assert out == [1,2,3,4,5,4,5,6,3,6,7,5,6,8,4,3]

对于a = [0, 1, 0]b = [None, 2, 3],这将生成

out == [0, 1, 3]

答案 2 :(得分:0)

尝试一下:

a = [1, 0, 3, 4, 0, 6, 7, 0, 9]
b = [1, 2, None, 4, 5, 6, None, 8, 9]

k = 0  # Counter
c = [0] * len(a)  # Creating the 'c' list
for n in a:  # Reading 'a' list
    if n != 0: 
        c[k] = a[k]  # Copying 'a' list objects, when 'n' != 0, in 'c' list
    else:
        c[k] = b[k]  # Copying 'b' list objects, when 'n' == 0, in 'c' list
    k = k + 1

答案 3 :(得分:0)

enumerate +循环+索引:

l=[i for i,v in enumerate(a) if v==0]
for i in l:
    a[i]=b[i]

现在:

print(a)

是:

[1, 2, 3, 4, 5, 4, 5, 6, 3, 6, 7, 5, 6, 8, 4, 3]