python - 从列表中删除值

标签 python python-3.x list

<分区>

我有以下问题:

我有一个列表:

temp= [950, 1000, 1100, 1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950, 2000, 2100, 2200]

在此列表中,我想删除所有 < 1200 and > 1950 的值.

我尝试了以下方法:

for x in temp:
    if x < 1200 or x > 1950:
        temp.remove(x)

这给了我以下结果:

[1000, 1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950, 2100]

但我的目标输出如下:

[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]

我找到了一种通过切片完成任务的方法:

new_temp = temp[temp.index(1200):temp.index(1950)+1]

这给了我想要的输出:

[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]

但我想了解为什么 attemp1 不起作用,是否有比 attemp2

更好的方法来完成我的任务

有人可以帮忙吗?提前致谢。

最佳答案

我会创建一个函数来识别有效值:

def validated(value):
    return 1200 <= value <= 1950

然后你可以在 list comprehension 中使用它:

>>> [value for value in temp if validated(value)]
[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]

或者您可以使用 filter

>>> list(filter(validated, temp))
[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]

编辑:您遇到问题的原因是您无法修改正在迭代的内容。它“不知道”您已经从它下面拉出地毯。

另一种方法是复制列表并对其进行迭代。

temp2 = temp[:]  # makes a copy
for x in temp2:
    if x < 1200 or x > 1950:
        temp.remove(x)

另外,remove 是一个线性搜索(很慢)。通常最好进行过滤。如果你真的需要修改 temp 引用的列表(而不是仅仅让 temp 指向不同的列表)你可以这样做:

temp[:] = [value for value in temp if validated(value)]

[:] 是一个切片运算符,如果您分配给它,它将替换原始列表的全部内容(而不是为名称分配一个新列表)。

关于python - 从列表中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53278963/

相关文章:

python - 返回分布的 z 值 - python

python - Python 中枚举的枚举?

python-3.x - 按特定月份切片

python - 以列格式将一个表的输出合并到另一个表

python - Pandas 时间序列 - 在每年的第一个值上添加一个值

python - 从 subprocess.run 解码 Python 中的特殊字符

python - 将列表中的字典添加到另一个列表中

python - 有没有办法连接子列表中的字符串列表

python - 是否可以将可移植 Python 32 位安装升级到 64 位安装?

python - 使用 python 验证 JSON 数据