首页 > 解决方案 > 从 Python 列表中的数组生成带有标签的对

问题描述

给定一个具有不同大小的数组列表,我想将一个数组中的对标记为相似 (1),将来自不同数组的对标记为不同 (0)。

假设我们有这个列表:

a = [[0, 1, 3],[4, 2]]

结果应如下所示:

pairs = [[0,1],[0,3],[0,4],[0,2],[1,0],[1,3],[1,4],...,[4,2],[4,1],...]
label = [1, 1, 0, 0, 1, 1, 0, ... , 1, 0, ...]

然而,对的顺序并不重要。

任何提示都会有所帮助!谢谢

标签: pythonarrayslistloops

解决方案


你可以试试这样的

from itertools import permutations

a=[[0,1,3],[4,2]]
a1=a[0]
a2=a[1]

a3=a1.copy()
a3.extend(a2)

perms=list(permutations(a3, 2))
print(perms)
new_arr = []

for i in perms:
    if (i[0] in a1 and i[1] in a1) or (i[0] in a2 and i[1] in a2):
        new_arr.append(1)
    else:
        new_arr.append(0)

print(new_arr)

推荐阅读