Python 3 中是否有“foreach”函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18294534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:25:01  来源:igfitidea点击:

Is there a 'foreach' function in Python 3?

pythonpython-3.xforeach

提问by user2003548

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

当我遇到我可以在javascript中完成的情况时,我一直在想如果有一个foreach功能就方便了。我所说的 foreach 指的是下面描述的函数:

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?

他们只是在每个元素上执行它并且没有产生或返回某些东西,我认为它应该是一个内置函数并且应该比用纯 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:

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

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

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

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

  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.
  1. 在正常情况下,人们只是不关心性能
  2. 有时 API 不接受可迭代对象,您无法重写其源代码。

回答by Phillip Cloud

Python doesn't have a foreachstatement per se. It has forloops built into the language.

Python没有一个foreach说法本身。它具有for内置于语言中的循环。

for element in iterable:
    operate(element)

If you really wanted to, you could define your own foreachfunction:

如果你真的想,你可以定义自己的foreach函数:

def foreach(function, iterable):
    for element in iterable:
        function(element)

As a side note the for element in iterablesyntax comes from the ABCprogramming language, one of Python's influences.

作为旁注,for element in iterable语法来自ABC编程语言,这是 Python 的影响之一。

回答by Jo Are By

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

我见过的每次出现的“foreach”(PHP、C#、...)都与 python 的“for”语句基本相同。

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".

所以,是的,python 中有一个“foreach”。称为“为”。

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

你所描述的是一个“数组映射”函数。这可以通过python 中的列表推导来完成:

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

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

回答by Akshit Khurana

mapcan be used for the situation mentioned in the question.

map可以用于问题中提到的情况。

E.g.

例如

map(len, ['abcd','abc', 'a']) # 4 3 1

For functions that take multiple arguments, more arguments can be given to map:

对于带有多个参数的函数,可以提供更多参数来映射:

map(pow, [2, 3], [4,2]) # 16 9

It returns a list in python 2.x and an iterator in python 3

它在 python 2.x 中返回一个列表,在 python 3 中返回一个迭代器

In case your function takes multiple arguments and the arguments are alreadyin the form of tuples (or any iterable since python 2.6) you can use itertools.starmap. (which has a very similar syntax to what you were looking for). It returns an iterator.

如果您的函数采用多个参数并且参数已经是元组的形式(或自 python 2.6 以来的任何可迭代),您可以使用itertools.starmap. (它的语法与您要查找的内容非常相似)。它返回一个迭代器。

E.g.

例如

for num in starmap(pow, [(2,3), (3,2)]):
    print(num)

gives us 8 and 9

给我们 8 和 9

回答by uingtea

Other examples:

其他例子:

Python Foreach Loop:

Python Foreach 循环:

array = ['a', 'b']
for value in array:
    print(value)
    # a
    # b

Python For Loop:

Python For 循环:

array = ['a', 'b']
for index in range(len(array)):
    print("index: %s | value: %s" % (index, array[index]))
    # index: 0 | value: a
    # index: 1 | value: b

回答by Be'ezrat Hashem

If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.

如果我理解正确,你的意思是如果你有一个函数“func”,你想检查列表中的每个项目,如果 func(item) 返回 true;如果你对所有人都是真的,那就做点什么。

You can use 'all'.

您可以使用“全部”。

For example: I want to get all prime numbers in range 0-10 in a list:

例如:我想在列表中获取 0-10 范围内的所有质数:

from math import sqrt
primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))]

回答by FooBar167

Look at this article. The iterator object nditerfrom numpypackage, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

看看这篇文章。迭代器对象nditernumpy的包,在NumPy的1.6引入,提供了许多灵活的方式来访问一个或多个阵列的所有元素以系统的方式。

Example:

例子:

import random
import numpy as np

ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])

for ptr in np.nditer(ptrs, op_flags=['readwrite']):
    # apply random shift on 1 for each element of the matrix
    ptr += random.choice([-1, 1])

print(ptrs)

d:\>python nditer.py
[[ -1   1]
 [399  -1]
 [  1 399]
 [399 401]]

回答by veera sai

This does the foreach in python 3

这在python 3中执行foreach

test = [0,1,2,3,4,5,6,7,8,"test"]

for fetch in test:
    print(fetch)

回答by aris

If you're just looking for a more concise syntax you can put the forloop on one line:

如果您只是在寻找更简洁的语法,您可以将for循环放在一行:

array = ['a', 'b']
for value in array: print(value)

Just separate additional statements with a semicolon.

只需用分号分隔附加语句。

array = ['a', 'b']
for value in array: print(value); print('hello')

This may not conform to your local style guide, but it could make sense to do it like this when you're playing around in the console.

这可能不符合您当地的风格指南,但是当您在控制台中玩弄时,这样做是有意义的。

回答by Caveman

Yes, although it uses the same syntax as a for loop.

是的,尽管它使用与 for 循环相同的语法。

for x in ['a', 'b']: print(x)

回答by user13067213

I think this answers your question, because it is like a "for each" loop.
The script below is valid in python (version 3.8):

我认为这回答了你的问题,因为它就像一个“for each”循环。
下面的脚本在python(3.8版)中有效:

a=[1,7,77,7777,77777,777777,7777777,765,456,345,2342,4]
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")