繁体   English   中英

如何通过比较每一行在二维数组中找到不同的数字?

[英]How to find the different number in a 2D array by comparing each row?

与二维数组中的所有其他行相比,输出只有该行具有的唯一编号。 例如:

list2d = [ 
    [5,9], 
    [1,5], 
    [1,5,7,8] 
]

>When doing for row 0, the output should be [9]  
>When doing for row 1, the output should be []  
>When doing for row 2, the output should be [7,8]  

基本上,这就是我所期望的:

list1 = [5,9]
list2 = [1,5]
list3 = [1,5,8,7]

print(set(list1).difference(list2).difference(list3))

但是,上述方法不能在循环中使用,因为我不知道将有多少行,因此无法将它们分成多个列表。

有办法解决吗? (最好不要使用附加包)

用:

list2d = [
    [5,9],
    [1,5],
    [1,5,7,8]
]


res = [set(lst).difference(*(lst2 for j, lst2 in enumerate(list2d) if j != i)) for i, lst in enumerate(list2d)]
print(res)

输出

[{9}, set(), {7, 8}]

选择:

res = []
for i, lst in enumerate(list2d):
    others = (lst2 for j, lst2 in enumerate(list2d) if j != i)
    diff = set(lst).difference(*others)
    res.append(diff)

第三种选择如下,使用collections.Counter

from collections import Counter

list2d = [
    [5, 9],
    [1, 5],
    [1, 5, 7, 8]
]

counts = Counter(ei for e in list2d for ei in e)

res = []
for lst in list2d:
    lst_counts = Counter(lst)
    res.append([e for e, c in lst_counts.items() if counts[e] == c])

print(res)

输出

[[9], [], [7, 8]]

最后一个替代方案的整体计算复杂度是O(n) 另请注意,可以使用默认字典类来实现此替代方法。

暂无
暂无

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

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