Python 3 中是否有“foreach"函数? [英] Is there a 'foreach' function in Python 3?

查看:35
本文介绍了Python 3 中是否有“foreach"函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到可以用javascript做的情况,总觉得如果有foreach函数就方便了.我所说的 foreach 指的是下面描述的函数:

When I meet the situation I can do it in javascript, I always think if there's an foreach function it would be convenience. By foreach I mean the function which is described below:

def foreach(fn,iterable):
    for x in iterable:
        fn(x)

他们只是在每个元素上都这样做,并没有产生或返回任何东西,我认为它应该是一个内置函数并且应该比用纯 Python 编写它更快,但我没有在上面找到它列表,或者它只是叫了另一个名字?或者我只是在这里错过了一些要点?

they just do it on every element and didn't yield or return something,i think it should be a built-in function and should be more faster than writing it with pure Python, but I didn't found it on the list,or it just called another name?or I just miss some points here?

也许我错了,导致在 Python 中调用函数的成本很高,对于示例来说绝对不是一个好习惯.函数应该在其主体内执行循环而不是输出循环,如下所示,这在许多 Python 的代码建议中已经提到:

Maybe I got wrong, cause calling an function in Python cost high, definitely not a good practice for the example. Rather than an out loop, the function should do the loop in side its body looks like this below which already mentioned in many python's code suggestions:

def fn(*args):
    for x in args:
       dosomething

但我认为 foreach 仍然受欢迎基于两个事实:

but I thought foreach is still welcome base on the two facts:

  1. 在正常情况下,人们并不关心性能
  2. 有时 API 不接受可迭代对象,您无法重写其源代码.

推荐答案

我见过的每次出现的foreach"(PHP、C#、...)与pythons的for"语句基本相同.

Every occurence of "foreach" I've seen (PHP, C#, ...) does basically the same as pythons "for" statement.

这些或多或少是等价的:

These are more or less equivalent:

// PHP:
foreach ($array as $val) {
    print($val);
}

// C#
foreach (String val in array) {
    console.writeline(val);
}

// Python
for val in array:
    print(val)

所以,是的,python 中有一个foreach".它被称为为".

So, yes, there is a "foreach" in python. It's called "for".

您所描述的是数组映射"函数.这可以通过 Python 中的 list comprehensions 来完成:

What you're describing is an "array map" function. This could be done with list comprehensions in python:

names = ['tom', 'john', 'simon']

namesCapitalized = [capitalize(n) for n in names]

这篇关于Python 3 中是否有“foreach"函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆