python - 如何获取二维列表中元组的索引?

标签 python list nested tuples

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

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

相关文章:

python - 了解 Odoo 中的 "takes at least X arguments (X given)"错误

javascript - 在 python 中模拟 javascript _dopostback,网络抓取

c# - 我读到过遍历 HashSet 是不好的做法。我应该先调用 .ToList() 吗?

c# - 如何将 IEnumerable<AnonymousType> 转换为 List<T>?

c - 嵌套结构中的指针

python - struct.unpack(struct.pack(float)) 有舍入误差?

python - xlwings - 获取和设置命名范围

python - 从现有列表创建新数组

java - 哪个类可以访问我的方法?

list - 带有 XML 数据源的表元素内的 Jasper 列表元素