如何在找到所有元素的第n个元素后返回true



我试图获得数组中的每个第n个元素,但由于返回true语句,函数停止迭代。

下面是我的代码:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def get_nth(n, array):
iterable_found = 0
for i in range(len(array)):
print(i)
if i == (iterable_found + n):
iterable_found += n

return True

return False

>>> print(get_nth(5, numbers))
0
1
2
3
4
5
True

但是我想让它遍历数组的其余部分并为10和15返回true。我计划通过一个while循环来运行这个函数,这样我就可以主动获取添加的第n个元素。谢谢你的帮助。

最小的例子:

从websocket流式传输数字的Csv文件

1
2
3
...

函数调用

import np
array = np.genfromtxt('feed.csv', delimiter = ',')
# loop for checking
while True:
print(get_nth(5, array))

我希望这有帮助,这是通过返回函数返回时留下的最后一个位置,并在再次调用最后一个位置时从那里拾取。

import random
numbers = [3, 7, 3, 111, 222, 333, 4444, 555, 9, 10, 11, 12, 13, 14, 15]

def get_nth(n, array, startPos):
for x in range(startPos, len(array)):
print(array[x])
if (array[x] % n) == 0:
return True, x
return False

pos = 0
while True:
if pos < len(numbers):
result, pos = get_nth(3, numbers, pos)
print(result)
pos += 1
# Works when adding numbers into the numbers list in the loop
# or your case your websocket
numbers.append(random.randint(0, 999))

输出
8
True
983
615
True
479
735
True
155

return关键字在函数执行后停止函数。为了避免这种情况,您可以将return关键字替换为yield。它将允许您将所有想要返回的值存储到类似于列表的东西中。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def get_nth(n, array):
iterable_found = 0
if len(array) >= n:
for i in range(len(array) + 1):
print(i)
if i == (iterable_found + n):
iterable_found += n
yield (True, i)
else:
yield False
list(get_nth(5, numbers))

return 关键字作为函数的结尾,因此根据您的需求,您不应该返回任何内容。相反,您可以创建一个空数组,并在找到可迭代对象

的地方添加数字。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
iterable_numbers = []
def get_nth(n, array):
iterable_found = 0
for i in range(len(array)):
print(i)
if i == (iterable_found + n):
iterable_found += n

iterable_numbers.append(i)

最新更新