我目前正在寻找一种从左到右比较列表元素的方法。
这是我的清单:
mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
我需要将第一个元素与所有其他元素进行比较,并检查是否有任何值匹配,第二个和第三个元素是否相同,依此类推,直到它到达列表的末尾。如果匹配,我需要将其打印出来。我需要打印出匹配的值和它匹配的索引。
例如。
index 0 matched with index 1 for value 15.
index 2 matched with index 5 for value 19
index 2 matched with index 6 for value 19
index 2 matched with index 6 for value 20
index 5 matched with index 6 for value 19.
我该怎么做呢?
答案 0 :(得分:3)
天真的解决方案是循环每一对,这很慢。但是,您可以采取以下措施:
这就是我的意思:
>>> mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
>>>
>>> pairs = dict()
>>>
>>>
>>> from collections import defaultdict
>>>
>>> pairs = defaultdict(list)
>>>
>>> for idx, sub in enumerate(mylist):
... for a in sub:
... pairs[a].append(idx)
...
>>> pairs
defaultdict(<type 'list'>, {65: [5], 3: [4], 13: [3], 14: [1], 15: [0, 1], 19: [2, 5, 6], 20: [2, 6], 31: [6]})
您可以忽略仅包含1个元素的值列表(因为这意味着我们没有一对)。具有2+元素的那些形成各种对。例如,对于19
,我们有[2, 5, 6]
含义:
就像你一样。此方法在嵌套列表中的项目总数中是线性的。如果嵌套列表长度有一个合理的上限,那么这就是主列表大小的O(n)。
现在输出:
>>> from itertools import combinations
>>>
>>> for k,v in pairs.iteritems():
... if len(v) > 1:
... for a,b in combinations(v, 2):
... print "Index {} matched with index {} for value {}".format(a, b, k)
...
Index 0 matched with index 1 for value 15
Index 2 matched with index 5 for value 19
Index 2 matched with index 6 for value 19
Index 5 matched with index 6 for value 19
Index 2 matched with index 6 for value 20
答案 1 :(得分:3)
您可以使用itertools.combinations
,它可以使您免于嵌套循环:
In [770]: l2=[(i,set(mylist[i])) for i in range(len(mylist))]
...: for (i, a), (j, b) in combinations(l2,2):
...: for v in a.intersection(b):
...: print "Index {} matched with index {} for value {}".format(i,j,v)
Index 0 matched with index 1 for value 15
Index 2 matched with index 5 for value 19
Index 2 matched with index 6 for value 19
Index 2 matched with index 6 for value 20
Index 5 matched with index 6 for value 19
答案 2 :(得分:2)
mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
my_set_list = [set(item) for item in mylist]
for i1, item in enumerate(my_set_list):
for i2 in xrange(i1 + 1, len(my_set_list)):
for val in (item & my_set_list[i2]):
print "Index {} matched with index {} for value {}".format(i1,i2,val)
<强>输出强>
Index 0 matched with index 1 for value 15.
Index 2 matched with index 5 for value 19.
Index 2 matched with index 6 for value 19.
Index 2 matched with index 6 for value 20.
Index 5 matched with index 6 for value 19.