Python:使用列表推导生成对称数组 [英] Python: Generating a symmetric array with list comprehension
问题描述
我正在尝试生成矩阵 A == [针对范围(0,n)中的i,j的f(i,j)]
.矩阵是对称(f(i,j)== f(j,i))
,对角线元素为零(f(i,i)== 0)
.
I am trying to generate a matrix A == [f(i,j) for i,j in range(0,n)]
. The matrix is symmetric (f(i,j) == f(j,i))
and the diagonal elements are zero (f(i,i) == 0)
.
问题:是否有可能产生一个列表理解,该列表生成会生成此矩阵,但只为 i<调用函数
? f(i,j)
.j
Question: Is it possible to produce a list comprehension that generates this matrix but that only calls the function f(i,j)
for i < j
?
不是我的问题:以其他方式生成对称矩阵.
Not my question: Generate the symmetric matrix in some other way.
可能的解决方案:通过辅助功能 g
调用 f
,该辅助功能保存了 f
的值存储在附加存储中或返回存储的值.
Possible solution: Make the call to f
through an auxiliary function g
that saves the value of f
in an additional storage or returns the stored value.
是否有可能解决避免额外存储的问题?我不确定是否有其他障碍意味着是否需要从自身引用列表理解(我读到的内容在Python中不存在),希望我还缺少其他技巧.
Would it be possible to solve avoiding the additional storage? I am not sure if this additional handicap implies that a reference to the list comprehension from itself (which I read doesn't exist in Python) is necessary, hopefully I am missing some other trick.
推荐答案
如果您希望函数仅在i<时执行.j,您可以使用lru_cache(@lru_cache)将函数的结果保存在缓存中,并在i> j时直接使用它而无需重新计算它.
If you want the function to execute only when i < j, you can use lru_cache (@lru_cache) to save the results of the function in cache, and use it directly without re-calculating it when i > j.
from typing import Any
from functools import lru_cache
@lru_cache()
def f(i: int, j: int) -> Any:
return i * (-j)
n = 5
m = [f(i, j) if i < j else f(j, i) if i > j else 0 for i in range(n) for j in range(n)]
for i in range(0, n * n, n):
print(m[i: i + n])
结果
[0, 0, 0, 0, 0]
[0, 0, -2, -3, -4]
[0, -2, 0, -6, -8]
[0, -3, -6, 0, -12]
[0, -4, -8, -12, 0]
这篇关于Python:使用列表推导生成对称数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!