[英]python : Find a skipped value in an array during a while loop
I have a while loop that runs through a fixed step and constantly checks if a value in an array is not equal to the while loop counter, and prints that number:我有一个 while 循环,它通过一个固定的步骤运行并不断检查数组中的值是否不等于 while 循环计数器,并打印该数字:
import numpy as np
values = [60.0, 75.8, 85.0, 90.0]
values = np.asarray(values)
counter = 50
while counter <= 100:
closest = (np.abs(values - counter)).argmin()
if (values[closest] > (counter - 1) and values[closest] <counter):
print("we skipped a value " + str(values[closest]))
counter = counter + 1
I wrote this code which has the mentioned functionality but it doesn't seem very elegant or efficient.我编写了具有上述功能的这段代码,但它似乎不是很优雅或高效。 Is there a quicker way to find these skipped values in Python?
有没有更快的方法在 Python 中找到这些跳过的值?
It's hard to tell from the question exactly what you need, but this produces the same output:很难从问题中确切地说出您需要什么,但这会产生相同的输出:
for v in sorted(set(values).difference(range(50, 101))):
print("we skipped a value " + str(v))
It creates a set
from the values
, removes every element between 50
and 100
inclusive, then prints any remaining values in ascending order.它从
values
创建一个set
,删除50
到100
之间的每个元素,然后按升序打印所有剩余的值。
This avoids looping and prints a list of skipped values:这避免了循环并打印跳过值的列表:
print("skipped values: " + str(values[np.isin(values, range(50, 101), invert=True)]))
numpy.isin
returns values from the first argument that are in the second argument. numpy.isin
从第二个参数中的第一个参数返回值。 Setting invert
to True
means return everything not in the second argument.将
invert
设置为True
意味着返回不在第二个参数中的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.