带有元素的Python列表操作

时间:2020-08-04 11:45:39

标签: python python-3.x list

我试图处理一个列表和一个循环。事实是,我有一个类似以下列表的列表= [9,3,5,2],我想对每个元素减去1 ...所以我已经尝试过类似的事情

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

4 个答案:

答案 0 :(得分:2)

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

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)

答案 1 :(得分:1)

使用列表理解

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

输出:

[8, 2, 4, 1]

答案 2 :(得分:0)

使用lambdamap

a = [9, 3, 5, 2]
x = list(map(lambda i: i-1, a))
print(x)

答案 3 :(得分:0)

如果您是python的新手,那么这是最简单的

client.on("ready", () => { 
  console.log(`${client.user.username} ready!`); 
  client.user.setActivity({ type: 'LISTENING' });
});

输出

a = [9, 3, 5, 2]
b=[]
for i in a:
    b.append(i-1)
print(b)