我需要获取彼此链接的元组位置,其中至少有一个元素。
[('1','1','1'),
('X','1','X'),
('Z','Z','Z'),
('Y','Y','X')]
这里,第一个元组中的值“1”出现在第二个元组中。 并且,现在在第二个元组中,值“X”出现在最后一个元组中。
因此,我需要将所有这些组合到一个列表中,而元组 3 值['Z'] 与任何其他元组都不匹配。因此,它存储在单独的列表中。
Expected : [[0,1,3],[2]]
我的方法:
df = [('1','1','1'),('X','1','X'),('Z','Z','Z'),('Y','Y','X')]
res = [list(sub) for sub in df]
res
count=0
list_A=[]
for i,j in enumerate(res):
for m,n in enumerate(j):
if res[i][m] in res[i]:
print(res.index(j))
最佳答案
试试这个代码:
df = [('1', '1', '1'), # 0
('X', '1', 'X'), # 1
('Z', 'Z', 'Z'), # 2
('Y', 'Y', 'X'), # 3
('Z', 'Z', 'Z'), # 4
('2', '2', '2')] # 5
# first gather all the sublist numbers that intersect
out = []
for x in df:
out.append({n for n, v in enumerate(df) if set(x).intersection(v)})
# then remove intersected (duplicated) sublist number subsets
output = []
while out:
buf = out.pop(0)
for x in out:
if buf & x: # intersection not empty
buf.update(x)
out.remove(x)
output.append(list(buf))
print(output)
输出:
[[0, 1, 3], [2, 4], [5]]
关于python - 如何获取二维列表中元组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980653/