问题:Python 3中是否有一个“ foreach”功能?

当我遇到这种情况时,我可以使用javascript做到这一点,我一直认为如果有一个foreach功能会很方便。通过foreach,我的意思是下面描述的功能:

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

他们只是在每个元素上执行它,而不产生或返回任何东西,我认为它应该是一个内置函数,并且应该比使用纯Python编写它要快,但我没有在列表中找到它,或者它只是叫另一个名字?还是我在这里想念一些要点?

也许我弄错了,导致在Python中调用函数的成本很高,绝对不是该示例的好习惯。该函数应该在其主体看起来像下面这样的循环中进行循环,而不是在out循环中进行下面的循环,这在许多python的代码建议中已经提到:

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

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

  1. 通常情况下,人们只是不在乎性能
  2. 有时,API不接受可迭代对象,因此您无法重写其源代码。

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.

回答 0

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

这些大致相同:

// 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”。它称为“ for”。

您要描述的是“数组映射”功能。这可以通过python中的列表理解来完成:

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

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

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]

回答 1

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

for element in iterable:
    operate(element)

如果确实需要,可以定义自己的foreach函数:

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

附带说明一下,for element in iterable语法来自ABC编程语言,这是Python的影响之一。

Python doesn’t have a foreach statement per se. It has for loops built into the language.

for element in iterable:
    operate(element)

If you really wanted to, you could define your own foreach function:

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

As a side note the for element in iterable syntax comes from the ABC programming language, one of Python’s influences.


回答 2

其他例子:

Python Foreach循环:

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

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

Other examples:

Python Foreach Loop:

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

Python For Loop:

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

回答 3

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

例如

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

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

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

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

如果您的函数接受多个参数,并且这些参数已经是元组形式(或者自python 2.6起是可迭代的),则可以使用itertools.starmap。(其语法与您要查找的语法非常相似)。它返回一个迭代器。

例如

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

给我们8和9

map can be used for the situation mentioned in the question.

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

In case your function takes multiple arguments and the arguments are already in 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.

E.g.

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

gives us 8 and 9


回答 4

这在python 3中做了foreach

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

for fetch in test:
    print(fetch)

This does the foreach in python 3

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

for fetch in test:
    print(fetch)

回答 5

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

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

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

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

回答 6

如果我没看错,您的意思是如果您具有函数’func’,则您想检查func(item)返回true时列表中的每一项;如果您对所有人都成立,那就做点什么。

您可以使用“全部”。

例如:我想获得列表中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))]

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.

You can use ‘all’.

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

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))]

回答 7

这是可以同时访问Python中元素索引“ foreach”构造示例:

for idx, val in enumerate([3, 4, 5]):
    print (idx, val)

Here is the example of the “foreach” construction with simultaneous access to the element indexes in Python:

for idx, val in enumerate([3, 4, 5]):
    print (idx, val)

回答 8

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

例:

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]]

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

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]]

回答 9

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

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

只需用分号分隔其他语句即可。

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

这可能不符合您的本地风格指南,但是在控制台中玩耍时这样做可能是有道理的。

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

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.


回答 10

我认为这回答了您的问题,因为它就像一个“ 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)")

I think this answers your question, because it is like a “for each” loop.
The script below is valid in python (version 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)")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。