简体   繁体   English

Python列表理解和list.remove()

[英]Python list comprehension and list.remove()

The list signals_by_date stores tuples and each tuple contains 15 numbers. 列表signals_by_date存储元组,每个元组包含15个数字。 For each tuple within signals_by_date, I want to remove numbers that don't satisfy certain criteria. 对于signals_by_date中的每个元组,我想删除不满足特定条件的数字。 For some reason, no matter what constraints I put in the list comprehension, I'm always left with 7 numbers in each tuple. 出于某种原因,无论我在列表理解中施加什么约束,每个元组中总是剩下7个数字。 In the code example below, all numbers are less than 3, so I would expect each tuple to be empty. 在下面的代码示例中,所有数字均小于3,因此我希望每个元组都为空。 What am I doing wrong? 我究竟做错了什么? Many thanks. 非常感谢。

    signals_by_date = []
    for i in range(0, 1):
        temp_signals = []
        for symbol in symbols:        
            for signal in signals_by_symbol[symbol]:
            temp_signals.append(signal[i]-1)
        signals_by_date.append(temp_signals)
        [signals_by_date[i].remove(v) for v in signals_by_date[i] if v < 3]

最后一行应为:

signals_by_date[i] = [v for v in signals_by_date[i] if v >= 3]

Presumably, as you remove each item you're shifting the items in the list such that you skip seeing every second one. 大概,在删除每个项目时,您正在移动列表中的项目,从而跳过了第二个项目。

In general, I believe list comprehensions are intended to accrue new lists from existing ones rather than to produce side effects on the items in the original list; 总的来说,我认为清单理解是为了从现有清单中获得新清单,而不是对原始清单中的项目产生副作用。 and certainly not to change the structure of the comprehended list. 并且肯定不会更改理解列表的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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