[英]Fastest way of interchanging 0s and 1s in a 2D list
Assume that I have a matrix: 假设我有一个矩阵:
[[1, 1, 1, 0, 0,], [0, 1, 0, 1], [1, 0, 1]]
and I would like it to change to: 我希望将其更改为:
[[0, 0, 0, 1, 1,], [1, 0, 1, 0], [0, 1, 0]]
What could possibly be the fastest way to deal with this case? 什么是处理此案的最快方法?
Currently, I use for loop in another for loop as following which is obviously too slow. 目前,我在另一个for循环中使用for循环 ,如下所示,这显然太慢了。
for my_row in my_mat:
for my_val in my_row:
my_val = 1 if my_val == 0 else 0
I don't think it's slow, but it isn't the fastest. 我不认为它很慢,但不是最快。 Here are a few faster alternatives.
这里有一些更快的选择。
>>> [[1 - j for j in i] for i in lst]
[[0, 0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0]]
This eliminates the need for an if
check. 这样就无需进行
if
检查。 Although, this would only make sense if you have a list of 0/1s and you only want to flip those values. 虽然,这只有在您有一个0/1列表并且只想翻转这些值时才有意义。
>>> [[j ^ 1 for j in i] for i in lst]
[[0, 0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0]]
XOR operations are fast in general, so this is a good alternative, if you have positive values beyond one. 通常,异或运算速度很快,因此,如果您的正值超过一个,则这是一个很好的选择。
not
Inversion not
反转 >>> [[int(not j) for j in i] for i in lst]
[[0, 0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0]]
Note that this squashes non-zero values to 1. The not
converts the integer to a truthy/falsy value, and the subsequent int
converts False
to 0
, or True
to 1
. 请注意,此南瓜非零值到1。
not
整数转换为truthy / falsy值,以及随后的int
转换False
到0
,或True
到1
。
If you're interested in performance of all the methods suggested here, 如果您对此处建议的所有方法的性能感兴趣,
lst = np.random.choice(2, (1000, 1000)).tolist()
%timeit [[int(not j) for j in i] for i in lst]
%timeit [[j ^ 1 for j in i] for i in lst]
%timeit [[1 - j for j in i] for i in lst]
10 loops, best of 3: 175 ms per loop
10 loops, best of 3: 89.8 ms per loop
10 loops, best of 3: 61.1 ms per loop
The fastest "algo" would be to leave your matrix untouched. 最快的“算法”是保持矩阵不变。 Just remember in a separate flag that every value you read (or write) has to be inverted.
只要记住在一个单独的标志中,您读取(或写入)的每个值都必须反转。 Done.
做完了
But if you physically need to invert each value in the matrix, then there's only one "algo" for that - the one you already discovered. 但是,如果您实际上需要反转矩阵中的每个值,则只有一个“算法”可以使用-您已经发现的一个。 The rest is not about "algo", it is about the most efficient implementation of that "algo".
其余与“算法”无关,而是与“算法”的最有效实现有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.