[英]How to find the different number in a 2D array by comparing each row?
Outputting the unique number(s) that only this row has, compared to all other rows in a 2D array.与二维数组中的所有其他行相比,输出只有该行具有的唯一编号。 For example:
例如:
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]
Basically, this is what I expected:基本上,这就是我所期望的:
list1 = [5,9]
list2 = [1,5]
list3 = [1,5,8,7]
print(set(list1).difference(list2).difference(list3))
However, the above method can't be used in a loop, since I don't know how many rows I will have so I can't separate them into multiple lists.但是,上述方法不能在循环中使用,因为我不知道将有多少行,因此无法将它们分成多个列表。
Is there a way to solve it?有办法解决吗? (better not use additional package)
(最好不要使用附加包)
Use:用:
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)
Output输出
[{9}, set(), {7, 8}]
Alternative:选择:
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)
A third alternative is the following, using collections.Counter :第三种选择如下,使用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)
Output输出
[[9], [], [7, 8]]
The overall computational complexity of this last alternative is O(n)
.最后一个替代方案的整体计算复杂度是
O(n)
。 Also note this alternative can be implemented using the default dictionary class.另请注意,可以使用默认字典类来实现此替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.