继承列表:创建除其他列表,整数和浮点数

2024-04-25 20:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够将整个列表除以整数、浮点数和Python中其他长度相等的列表,因此我编写了以下小脚本。你知道吗

class divlist(list):
    def __init__(self, *args, **kwrgs):
        super(divlist, self).__init__(*args, **kwrgs)
        self.__cont_ = args[0]
        self.__len_ = len(args[0])

    def __floordiv__(self, other):
        """ Adds the ability to floor divide list's indices """
        if (isinstance(other, int) or isinstance(other, float)):
            return [self.__cont_[i] // other \
                for i in xrange(self.__len_)]
        elif (isinstance(other, list)):
            return [self.__cont_[i] // other[i] \
                for i in xrange(self.__len_)]
        else:
            raise ValueError('Must divide by list, int or float')

我的问题是:我怎样才能用一种更简单的方式来写呢?我真的需要self.__cont_self.__len_行吗?我在查看列表中的“魔法”方法,却找不到一个能轻易保存这些信息的方法。你知道吗

调用此简单类的示例:

>>> X = divlist([1,2,3,4])
[1, 2, 3, 4]
>>> X // 2
[0, 1, 1, 2]
>>> X // [1,2,3,4]
[1, 1, 1, 1]
>>> X // X
[1, 1, 1, 1]

Tags: orself列表leninitdefargslist
2条回答

与其检查每个参数的显式类型,不如假设第二个参数是iterable,或者它是一个合适的值作为//的分母。你知道吗

def __floordiv__(self, other):
    try:
        pairs = zip(self, other)
    except TypeError:
        pairs = ((x, other) for x in self)
    return [x // y for (x, y) in pairs]

如果zip成功,您可能需要检查selfother的长度是否相同。你知道吗

How can I write this in a simpler way?

self[i]代替self.__cont_[i]。你知道吗

Do I really need the lines self.__cont_ and self.__len_?

不需要。只需要使用引用列表的常规方法,例如:[]len()。你知道吗

另外,您可以选择让.__floordiv__()返回divlist而不是list,这样您就可以继续对结果进行操作。你知道吗

class divlist(list):
    def __floordiv__(self, other):
        """ Adds the ability to floor divide list's indices """
        if (isinstance(other, int) or isinstance(other, float)):
            return [i // other for i in self]
        elif (isinstance(other, list)):
            # DANGER: data loss if len(other) != len(self) !!
            return [i // j for i,j in zip(self, other)]
        else:
            raise ValueError('Must divide by list, int or float')

X = divlist([1,2,3,4])
assert X == [1, 2, 3, 4]
assert X // 2 == [0, 1, 1, 2]
assert X // [1,2,3,4] == [1, 1, 1, 1]
assert X // X == [1, 1, 1, 1]

相关问题 更多 >