python 对象列表的中缀运算符
python infix operator on a list of objects
我在 jupyter notebook 中使用数学优化库 (PICOS)。
在 PICOS 中,符号 //
和 &
是垂直和水平连接的中缀运算符,用于从块中构建矩阵。请注意,我不能使用 numpy.bmat
因为这些块不是 numpy 对象。
如果我有一个块列表,例如 [A,B,C]
,我会通过使用符号 A & B & C
水平连接它们来形成一个矩阵。当列表包含数百个符号并且我无法手动构建矩阵时,问题就出现了。有没有一种简单的方法可以在列表中的每个符号之间插入一个中缀?
'&'.join([A,B,C])
或
' & '.join([A,B,C])
如果你想要 &
之间有空格
编辑:
也包在里面eval
eval(' & '.join([A,B,C]))
我应该不那么仓促。我只是用递归函数做的:
def concat_horizontal(lst):
if len(lst) == 2:
return lst[0] & lst[1]
else:
return concat_horizontal([lst[0] & lst[1]] + lst[2:])
和一个类似的垂直串联。耶,递归!
使用 built-in reduce
元函数(Python 2.7 docu, Python 3 docu) with the operators.and_(a, b)
表示 &
中缀运算符作为两个参数的函数:
from functools import reduce
from operators import and_
def concat_horizontal(iterable_of_affine_expressions):
return reduce(and_, iterable_of_affine_expressions)
我在 jupyter notebook 中使用数学优化库 (PICOS)。
在 PICOS 中,符号 //
和 &
是垂直和水平连接的中缀运算符,用于从块中构建矩阵。请注意,我不能使用 numpy.bmat
因为这些块不是 numpy 对象。
如果我有一个块列表,例如 [A,B,C]
,我会通过使用符号 A & B & C
水平连接它们来形成一个矩阵。当列表包含数百个符号并且我无法手动构建矩阵时,问题就出现了。有没有一种简单的方法可以在列表中的每个符号之间插入一个中缀?
'&'.join([A,B,C])
或
' & '.join([A,B,C])
如果你想要 &
编辑:
也包在里面eval
eval(' & '.join([A,B,C]))
我应该不那么仓促。我只是用递归函数做的:
def concat_horizontal(lst):
if len(lst) == 2:
return lst[0] & lst[1]
else:
return concat_horizontal([lst[0] & lst[1]] + lst[2:])
和一个类似的垂直串联。耶,递归!
使用 built-in reduce
元函数(Python 2.7 docu, Python 3 docu) with the operators.and_(a, b)
表示 &
中缀运算符作为两个参数的函数:
from functools import reduce
from operators import and_
def concat_horizontal(iterable_of_affine_expressions):
return reduce(and_, iterable_of_affine_expressions)