在python中查找最接近的元组元素出现的索引

时间:2017-06-13 06:24:24

标签: python templates indexing tuples elements

R = [(1,2),(1,3),(1,4),(1,5),(1,6),(2,3),(2,4),(2) ,5),(2,6),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)]

来自上面的LIST R,我需要找到每个元组的最近索引,其中没有出现任何元素。我的意思是没有元组的值相同。并且这个元组的顺序也是固定的。

最后当我们组合三个元组时,我们应该拥有所有的源元素(1,2,3,4,5,6)

预期产出:

表示0:(0,9,14):( 1,2)(3,4)(5,6) 1:(1,6,14):( 1,3)(2,4)(5,6) 。 。 。 。 对于4 :( 4,2,12):( 1,2)(3,4)(5,6) 。 。 。等等

请帮助......谢谢。

我尝试过的东西太大了,我自己也不满意

for j in range(i+1,i+10):
    b=set(Results[j])
    if (len(a&b)==0):

        for k in range(i+10, i+200):
            c=set(Results[k])
            if ( (len(a&c)==0) and (len(b&c)==0) ):

                for l in range(i+200, i+600):
                    d=set(Results[l])
                    if ( (len(a&d)==0) and (len(b&d)==0)  and (len(c&d)==0) ):

1 个答案:

答案 0 :(得分:1)

这摆脱了你的一个嵌套循环。我不知道您从哪里获取i值,或者为什么在内循环上使用如此大的范围。

R = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
# keep track of the indices where tuple elements are disjoint
matches = {}
# loop over R
for index in range(len(R)):
  # track the elements seen so far
  elements = set(R[index])
  # track the index where elements were seen
  matches[index] = [index]
  # loop over subsequent items
  for _index in range(index, len(R)):
    # if the tuple has all items not already seen, record it
    if elements.isdisjoint(set(R[_index])):
      elements = elements.union(R[_index])
      matches[index] += [_index]
# discard anything that does not have all six items
final_matches = {k: v for k, v in matches.viewitems() if len(v) == 3}