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

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

问题描述

当我遇到这种情况时,我可以用javascript来做,我总是认为如果有一个 foreach 函数,这将是方便的。通过foreach,我的意思是下面描述的函数:

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

他们只是在每个元素上做,而不是产生或返回的东西,我认为它应该是一个内置函数,应该比用纯Python编写速度更快,但是我没有在列表中找到它,或者只是调用另一个名称?或者我只是想念一些这里指的是什么?



也许我错了,因为用Python调用函数的代价很高,对于这个例子绝对不是一个好习惯。而不是一个循环,这个函数应该在下面的循环体中看起来像下面这样在很多python的代码中已经提到了:
$ b $ $ pre $ $ c $ def fn(* args):
for args:
dosomething

但是我认为foreach仍然是基于以下两个事实的欢迎:


  1. 在正常情况下,人们并不关心性能

  2. 有时API不接受iterable对象,您不能重写它的源代码。



这些或多或少是等价的:

  // PHP:
foreach($数组为$ val){
print($ val);


C#
foreach(数组中的字符串val){
console.writeline(val);


// Python
用于数组中的val:
print(val)

所以,是的,Python中有一个foreach。它被称为for。

你所描述的是一个数组映射函数。这可以通过Python中的列表解析完成:

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

namesCapitalized = [大写(n) ]


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)

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?

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

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

  1. In normal cases, people just don't care about the performance
  2. Sometime the API didn't accept iterable object and you can't rewrite its source.

解决方案

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)

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

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天全站免登陆