在同一列表上应用具有两个参数的函数,并仅输出没有对角线的下/上三角矩阵

问题描述 投票:0回答:1

我想比较字符串而不进行不必要的比较,到目前为止我已经:

[[[dice_coefficient(x,y) for x in ['a','a','b'][j]] for y in ['a','a','b'][0:j]] for j in [1,2]]

其中

dice_coefficient
定义为 here

它给出了预期的输出,但看起来并不具有可扩展性。

python list-comprehension apply
1个回答
0
投票

有一件事是,在您的情况下,外循环的第一次迭代(

for j ...
)是第二次迭代的子集。要仅比较一次,您可以这样做:

data = ['a', 'a', 'b']
[
    [
        dice_coefficient(x, y)
        for x in data[i:]
    ]
    for i, y in enumerate(data[:-1], start=1)
]

如果您认为

data
中有很多重复值,您可以在 lru_cache
 上使用 
dice_coefficient
 来避免重复比较。

© www.soinside.com 2019 - 2024. All rights reserved.