说我有一个列表如下:
list = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]
我想获得包含唯一元素的内部列表的索引。对于上面的示例,索引2处的列表是唯一包含7的列表,索引3处的列表是唯一包含6的列表。
如何在python中实现它?
答案 0 :(得分:4)
以下是使用Counter
的解决方案。检查每个内部列表中是否只有一个计数的值,然后打印相应的索引(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]
可能的优化可能包括预先计算集合中的唯一元素,以使用any
替换set.intersection
调用。
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)]
答案 1 :(得分:1)
天真的解决方案:
>>> 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]
答案 2 :(得分:0)
将itertools.chain
与set.difference(set)
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]