如果数组中的所有变量都匹配另一个数组中的变量,如何退出 While 循环 (python)
如果数组的列中的所有值都与另一个数组的列匹配,我尝试进入/退出 while 循环。
例如,我有;
import numpy as np
ColumnA = np.array([[1], [1], [1], [-1], [-1], [1]])
ColumnB = np.array([[1], [1], [1], [-1], [-1], [-5]])
iterations = 10
count = 0
while iterations != count:
count = count + 1
print (count)
while ColumnA.all() != ColumnB.all():
ColumnB = ColumnB[0, 5] + 1
print(ColumnB)
print("Exit")
print(count)
我期望这段代码进入嵌套的 while 循环,因为 ColumnA[0, 5] 不等于 ColumnB[0, 5],然后 ColumnB[0, 5] 加 1 直到匹配 ColumnA[ 0, 5] 此时退出 while 循环。
此代码不会进入 while 循环,因此我假设它认为 ColumnA.all() 与 ColumnB.all() 相同。我的猜测是它只是查看数组的第一个值,但我希望它匹配数组的所有部分以退出循环。
感谢您的帮助。
I am trying to enter/exit a while loop if all the values in a column of an array match the column of another array.
For Example, I have;
import numpy as np
ColumnA = np.array([[1], [1], [1], [-1], [-1], [1]])
ColumnB = np.array([[1], [1], [1], [-1], [-1], [-5]])
iterations = 10
count = 0
while iterations != count:
count = count + 1
print (count)
while ColumnA.all() != ColumnB.all():
ColumnB = ColumnB[0, 5] + 1
print(ColumnB)
print("Exit")
print(count)
What I would expect is for this code to enter that nested while loop, since ColumnA[0, 5] does not equal ColumnB[0, 5], and then for ColumnB[0, 5] to increase by 1 until it matchs ColumnA[0, 5] at which point it exits the while loop.
This Code does not enter the while loop, so I'm assuming it thinks ColumnA.all() is the same as ColumnB.all(). My guess is that it's just looking at the first value of the array, but I want it to match all parts of the array to exit the loop.
Thank you for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
ColumnA.all()
您只需检查ColumnA
中的所有元素是否都计算为 true。ColumnA
和ColumnB
就是这种情况。因此,ColumnA.all() == ColumnB.all()
的计算结果为True == True
,这当然是正确的。您需要按元素进行比较,然后检查获得的布尔向量的所有元素是否为 True:此外您的索引也是错误的。您的数组是 6x1,因此如果您想要最后一个元素,则需要
[5, 0]
而不是[0, 5]
。With
ColumnA.all()
you're only checking whether all elements inColumnA
evaluate to true. That is the case inColumnA
as well asColumnB
. SoColumnA.all() == ColumnB.all()
evaluates toTrue == True
, which of course is true. You need to compare elementwise and then check if all elements of the boleean vector that you get areTrue
:Also your index is wrong. Your arrays are 6x1, so if you want the last element you need
[5, 0]
not[0, 5]
.