Python:将列表中的元素与其他元素进行比较

2024-04-27 14:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来比较从左到右的列表元素。

这是我的名单:

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.

我该怎么做呢?


Tags: 方法元素列表forindexvaluewith末尾
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
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.

天真的解决方案是循环遍历每一对,这是很慢的。但是,您可以按照以下思路执行操作:

  • 创建一个dict,将int(嵌套列表中的元素)映射到包含master中列表索引的列表。
  • 循环主列表,对于每个子列表,将其索引添加到对应于dict中每个元素的spot
  • 现在,dict的值由列表组成,其中每两个元素都是一个“对”。

这就是我的意思:

>>> 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]的含义:

  • 2和5是一对
  • 2和6是一对
  • 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

相关问题 更多 >