简体   繁体   English

在List子类的方法中对“ self”进行切片的正确方法是什么?

[英]What's the proper way to slice `self` within a method of a List subclass?

I intend to create a method to slice a list , however I don't have the correct syntax here, and I haven't been able to come up with the correct search query to find out how to do this: 我打算创建一种对list进行切片的方法,但是我这里没有正确的语法,而且我无法提出正确的搜索查询来找出执行此操作的方法:

class BarList(list):
    """Items in the list are always in ascending order of .date"""
    def trim(self, start:dt.datetime=None, end:dt.datetime=None):
        """Removes all bars before `start` and after `end`"""
        if start:
            for i, bar in enumerate(self):
                if bar.date >= start:
                    self = self[i:]
                    break

What's the proper way to do what I'm trying to express in the above pseudocode? 什么是我要在上面的伪代码中表达的正确方法?

The reason why self = self[i:] is incorrect is because all it does is slice the list and assign that slice to a local variable named self . self = self[i:]之所以不正确,是因为它所做的只是对列表进行切片并将该切片分配给名为self的局部变量。 It doesn't actually modify the list. 它实际上并没有修改列表。

In order to change the content of the list, you can use a slice assignment : 为了更改列表的内容,可以使用切片分配

self[:] = self[i:]

This basically means "replace the entire content of the list with the value on the right side of the = symbol". 这基本上意味着“将列表的整个内容替换为=符号右侧的值”。


The other part of the problem is making your trim method work correctly. 问题的另一部分是使trim方法正常工作。 There are a few cases that your code doesn't handle. 在某些情况下,您的代码无法处理。 Here's the updated code: 这是更新的代码:

import datetime as dt

class BarList(list):
    """Items in the list are always in ascending order of .date"""
    def trim(self, start:dt.datetime=None, end:dt.datetime=None):
        """Removes all bars before `start` and after `end`"""
        if start:
            for i, bar in enumerate(self):
                if bar >= start:
                    # if this date is later than `start`, remove
                    # everything up to here
                    self[:] = self[i:]
                    break
            else:
                # if no date greater than `start` was
                # found, delete everything
                del self[:]

Test run: 测试运行:

l = BarList([dt.datetime.now()])
print(l)  # output: [datetime.datetime(2018, 4, 19, 0, 18, 14, 23474)]
l.trim(dt.datetime.now())
print(l)  # output: []

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

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