gpt4 book ai didi

python - 在 numpy 数组的 python 列表中快速查找联合对

转载 作者:行者123 更新时间:2023-12-01 09:02:48 25 4
gpt4 key购买 nike

我有一个 numpy 数组列表,想要获取关节对的索引。基本上,如果我有以下列表:

lst = [[1, 2, 3, 5], [1, 2, 9], [5, 6], [9]]

我想要以下内容:

[[0, 1], [0, 2], [1, 3]]

这是我到目前为止所拥有的,但速度很慢:

out = out
for i, item in enumerate(lst):
for j in range(i+1, len(lst)):
if not set(item).isdisjoint(lst[j]):
out.append([i, j])

感谢您的帮助。

最佳答案

你可以尝试这样的事情:

from itertools import combinations

lst = [[1, 2, 3, 5], [1, 2, 9], [5, 6], [9]]
lst_set = [set(e) for e in lst]

print([[x, y] for x, y in combinations(range(len(lst)), 2) if not lst_set[x].isdisjoint(lst_set[y])])

输出

[[0, 1], [0, 2], [1, 3]]

关于python - 在 numpy 数组的 python 列表中快速查找联合对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52334593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com