我希望能够在 Python 中将整个列表除以整数、 float 和其他长度相等的列表,因此我编写了以下小脚本。
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]
请您参考如下方法:
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]
