首页 > 解决方案 > 带有元素的 Python 列表操作

问题描述

我试图用一个列表和一个循环来操作。问题是我有一个类似于以下 a = [9, 3, 5, 2] 的列表,我想为每个元素减去 1...所以我尝试了类似这样的方法

a = [9, 3, 5, 2]
b = -1
x = a - b

标签: pythonpython-3.xlist

解决方案


有点超出您实际问题的范围,但您可以使用一些魔术函数来抽象出细节:

class MyCoolList(list):
    def __sub__(self, other):
        return [item - other for item in self]

    def __add__(self, other):
        return [item + other for item in self]

    def __mul__(self, other):
        return [item * other for item in self]

现在我们可以这样做:

cls = MyCoolList([9, 3, 5, 2])

print(cls - 1)
print(cls + 1)
print(cls * 2)

哪个产量

[8, 2, 4, 1]
[10, 4, 6, 3]
[18, 6, 10, 4]

为了不重复自己(DRY),您可以很好地使用该operator模块:

import operator as op


class MyCoolList(list):
    def calc(self, what, other):
        return [what(item, other) for item in self]

    def __sub__(self, other):
        return self.calc(op.sub, other)

    def __add__(self, other):
        return self.calc(op.add, other)

    def __mul__(self, other):
        return self.calc(op.mul, other)

最后,您可以完全使用装饰器:

import operator as op

def calc(operator_function):
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            lst, other = args
            return [operator_function(item, other) for item in lst]

        return wrapper

    return real_decorator


class MyCoolList(list):

    @calc(op.sub)
    def __sub__(self, other):
        pass

    @calc(op.add)
    def __add__(self, other):
        pass

    @calc(op.mul)
    def __mul__(self, other):
        pass


cls = MyCoolList([9, 3, 5, 2])
print(cls - 1)
print(cls + 1)

推荐阅读