python - 从数组中中断并在 python 中运行另一个函数

标签 python python-2.x

我的代码:

def exit():
   return "Exit" 

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

def func():
   for element in arr:
      print element

我想在数组的每 3 个元素之后运行 exit(),然后从最后一个元素恢复。

最佳答案

您可以使用 enumerate和模:

def exit():
    return "Exit"


arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

def func():
    for ind, element in enumerate(arr, 1):
        print element
        if ind % 3 == 0:
            print(exit())

输出:

1
2
3
Exit
4
5
6
Exit
7
8
9
Exit
0

如果你真的想一次使用 n 个元素,可以将它们传递给一个函数:

from itertools import islice

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

def func():
    it = iter(arr)
    for sli in iter(lambda: list(islice(it, 3)),[]):
        print(sli) # pass sli to function
        print(exit())

func()

输出:

[1, 2, 3]
Exit
[4, 5, 6]
Exit
[7, 8, 9]
Exit
[0]
Exit

关于python - 从数组中中断并在 python 中运行另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373995/

相关文章:

python - Python 中的整数除法

python - 我无法使用 python 将空字符串转换为整数

python - 更改 python fileConfig 记录器的级别

python - 使用Python字典值返回键作为结果

Python3.7 - 如何从字节码的代码对象中获取函数签名?

仅在 PC 启动时出现 Python 错误 sqlite3.OperationalError : unable to open database file

python - 从存档文件中有条件提取文件

python - 避免在 python 中为 Long 加上 L 后缀

python - 将带有内部空字符的 python2.7 字符串传递给 C++

python - Seaborn猫图: change position on x axis