python - 带有元素的 Python 列表操作
问题描述
我试图用一个列表和一个循环来操作。问题是我有一个类似于以下 a = [9, 3, 5, 2] 的列表,我想为每个元素减去 1...所以我尝试了类似这样的方法
a = [9, 3, 5, 2]
b = -1
x = a - b
解决方案
有点超出您实际问题的范围,但您可以使用一些魔术函数来抽象出细节:
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)
推荐阅读
- image - 如何在树枝模板中显示图像 GD 资源
- linker - 手动编译OpenSSL:制作共享对象时不能使用符号;使用 -fPIC 重新编译
- ocr - 为什么 Microsoft Cognitive 不返回每个 OCR 字段?
- angular - 在环境上下文中不允许使用 Angular2 打字稿错误初始化程序
- swift - 在单独文件中定义的 Swift 结构是否需要初始化程序?
- autodesk-forge - 下载衍生文件时的 HTTP 状态码
- docker - docker-compose.yml 中指定的资源限制没有被 docker 考虑
- javascript - ChartJS 在 show() 调用时重放图表动画
- c# - 如何替换文本文件中的特定行?
- python - 将具有数字和一些破折号的列转为 int?