简体   繁体   English

在python列表列表中查找包含唯一元素的列表?

[英]Finding list containing unique elements in list of lists in python?

Say I have a list of lists like so: 说我有一个像这样的清单清单:

list = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]

I want to get the indices of the inner lists that contain unique elements. 我想获取包含唯一元素的内部列表的索引。 For the example above, the lists at index 2 is the only one that contains 7 and the list at index 3 is the only one that contains 6. 对于上面的示例,索引2的列表是唯一包含7的列表,索引3的列表是唯一包含6的列表。

How would one go about implementing this in python? 如何在python中实现呢?

Here's a solution using Counter . 这是使用Counter的解决方案。 Each inner list is checked for a value that only has a single count, and then the corresponding index is printed (a la enumerate ). 检查每个内部列表的值是否只有一个计数,然后打印相应的索引(la enumerate )。

from collections import Counter
from itertools import chain

c = Counter(chain.from_iterable(l))
idx = [i for i, x in enumerate(l) if any(c[y] == 1 for y in x)] 

print(idx)
[0, 2, 3]

A possible optimisation might include precomputing unique elements in a set to replace the any call with a set.intersection . 可能的优化可能包括预先计算集合中的唯一元素,以用set.intersection替换any调用。

c = Counter(chain.from_iterable(l))
u = {k for k in c if c[k] == 1}

idx = [i for i, x in enumerate(l) if u.intersection(x)]

A naive solution: 一个幼稚的解决方案:

>>> from collections import Counter
>>> from itertools import chain
>>> my_list = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]
# find out the counts.
>>> counter = Counter(chain(*my_list))
# find the unique numbers
>>> uniques = [element for element,count in counter.items() if count==1]
# find the index of those unique numbers
>>> result = [indx for indx,elements in enumerate(my_list) for e in uniques if e in elements]
>>> result
[0, 2, 3]

using itertools.chain with set.difference(set) 使用带有set.difference(set) itertools.chain

from itertools import chain
l = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]
[i for i in range(len(l)) if set(l[i]).difference(set(chain(*[j for j in l if j!=l[i]])))]
#[0, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM