我想比较字符串而不进行不必要的比较,到目前为止我已经:
[[[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
它给出了预期的输出,但看起来并不具有可扩展性。
有一件事是,在您的情况下,外循环的第一次迭代(
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
来避免重复比较。