在 python 中找到元组元素未出现的最近索引
Find nearest index of non occurrence of the elements of the tuple in python
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) ):
这摆脱了您的嵌套循环之一。我不知道你从哪里得到 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}
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) ):
这摆脱了您的嵌套循环之一。我不知道你从哪里得到 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}