python foreach,Python 3中是否有“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)

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:

In normal cases, people just don't care about the performance

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值