gpt4 book ai didi

python - 根据过滤器从python列表中删除元素

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:18 24 4
gpt4 key购买 nike

我有 3 个 Python 列表。

list_a = [10., 20., 30., 12.]
list_b = [30., 20., 60., 12.]
list_c = [10., 80., 90., 12.]

我想将这些元素放入 list_b 中和 list_c list_a 中的值是 <= 15 .因此结果变为:

list_b = [20., 60.]
list_c = [80., 90.]

有没有不用 for 循环的方法? (列表理解没问题)

最佳答案

如果你像你说的那样使用 numpy,在注释中,你可以简单地从 a 创建一个 bool 索引,并屏蔽 bc 中的元素:

import numpy as np

list_a = np.array([10., 20., 30., 12.])
list_b = np.array([30., 20., 60., 12.])
list_c = np.array([10., 80., 90., 12.])

list_b = list_b[list_a>15]
list_c = list_c[list_a>15]

print list_a
print list_b
print list_c

输出:

[ 10.  20.  30.  12.]
[ 20. 60.]
[ 80. 90.]

您可以通过.tolist() 方法将lists_blist_c 转换为Python list type

关于python - 根据过滤器从python列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41423992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com