Python:根据元素的条件在两个列表中选择元素

lpwwtiir  于 2023-05-05  发布在  Python
关注(0)|答案(3)|浏览(133)

我有两个清单:

a = [1,-1,-1, 2,-1]
b = [3, 5, 4, 6, 7]

我想得到一个新的列表c,其值为b if a == -1 else 0

c = [0, 5, 4, 0, 7]
kulphzqa

kulphzqa1#

你可以使用一个列表解析和一个三元:

c = [val_b if val_a == -1 else 0 for val_a, val_b in zip(a, b)]

输出:

[0, 5, 4, 0, 7]
f4t66c6m

f4t66c6m2#

列出组件+枚举:

a = [1,-1,-1, 2,-1]
b = [3, 5, 4, 6, 7]
[b[x] if a[x]==-1 else 0 for x,y in enumerate(a)]

#[0, 5, 4, 0, 7]
9ceoxa92

9ceoxa923#

也许这会起作用:

a = [1, -1, -1, 2, -1]
b = [3, 5, 4, 6, 7]
c = []

i = 0

while i < len(a):
    if a[i] == -1:
        c.append(b[i])
    else:
        c.append(0)
    i += 1

print(c)

相关问题