我希望能够将整个列表除以整数、浮点数和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]
与其检查每个参数的显式类型,不如假设第二个参数是iterable,或者它是一个合适的值作为
//
的分母。你知道吗如果
zip
成功,您可能需要检查self
和other
的长度是否相同。你知道吗用
self[i]
代替self.__cont_[i]
。你知道吗不需要。只需要使用引用列表的常规方法,例如:
[]
和len()
。你知道吗另外,您可以选择让
.__floordiv__()
返回divlist
而不是list
,这样您就可以继续对结果进行操作。你知道吗相关问题 更多 >
编程相关推荐