首页 > 解决方案 > 如何获取二维列表中元组的索引?

问题描述

我需要获取相互链接的元组位置,其中至少有一个元素。

 [('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))

标签: pythonlistnestedtuples

解决方案


试试这个代码:

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]]

推荐阅读