如果数组中的所有变量都匹配另一个数组中的变量,如何退出 While 循环 (python)

发布于 2025-01-15 22:32:18 字数 678 浏览 4 评论 0原文

如果数组的列中的所有值都与另一个数组的列匹配,我尝试进入/退出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2025-01-22 22:32:18

使用 ColumnA.all() 您只需检查 ColumnA 中的所有元素是否都计算为 true。 ColumnAColumnB 就是这种情况。因此,ColumnA.all() == ColumnB.all() 的计算结果为 True == True,这当然是正确的。您需要按元素进行比较,然后检查获得的布尔向量的所有元素是否为 True:

while not all(ColumnA == ColumnB):
    ...

此外您的索引也是错误的。您的数组是 6x1,因此如果您想要最后一个元素,则需要 [5, 0] 而不是 [0, 5]

With ColumnA.all() you're only checking whether all elements in ColumnA evaluate to true. That is the case in ColumnA as well as ColumnB. So ColumnA.all() == ColumnB.all() evaluates to True == True, which of course is true. You need to compare elementwise and then check if all elements of the boleean vector that you get are True:

while not all(ColumnA == ColumnB):
    ...

Also your index is wrong. Your arrays are 6x1, so if you want the last element you need [5, 0] not [0, 5].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文