标签归档:foreach

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

问题: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)")

相当于Python foreach

问题:相当于Python foreach

我正在研究Python,并且有一个关于foreach迭代的问题。我是Python的新手,我在C#中有一些经验。所以我想知道,Python中是否有一些等效函数可用于集合中所有项目的迭代,例如

pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]

或类似的东西。

I am diving into Python and I have a question about foreach iteration. I am new to Python and I have some experience in C#. So I am wondering, if there is some equivalent function in Python for iteration all over all items in my collection, e.g.

pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]

or something like this.


回答 0

当然。一个for循环。

for f in pets:
    print f

Sure. A for loop.

for f in pets:
    print f

回答 1

像这样:

for pet in pets :
  print(pet)

实际上,Python 具有foreach样式for循环。

Like this:

for pet in pets :
  print(pet)

In fact, Python only has foreach style for loops.


回答 2

观察这一点也很有趣

要遍历序列的索引,可以结合使用range()len()如下所示:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
  print(i, a[i])

输出

0 Mary
1 had
2 a
3 little
4 lamb

编辑#1:替代方法:

在序列中循环时,可以使用enumerate()函数同时检索位置索引和相应的值。

for i, v in enumerate(['tic', 'tac', 'toe']):
  print(i, v)

输出

0 tic
1 tac
2 toe

Its also interesting to observe this

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
  print(i, a[i])

output

0 Mary
1 had
2 a
3 little
4 lamb

Edit#1: Alternate way:

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
  print(i, v)

output

0 tic
1 tac
2 toe

回答 3

对于更新的答案,您可以forEach轻松地在Python中构建一个函数:

def forEach(list, function)
  for i,v in enumerate(list))
    function(v, i, list)

你也可以适应这mapreducefilter,并从其他语言或任何其他优先的阵列功能,你想带过来。for循环足够快,但是模板要比forEach其他功能更长。您还可以扩展列表以使用指向类的局部指针来具有这些功能,因此也可以直接在列表上调用它们。

For an updated answer you can build a forEach function in Python easily:

def forEach(list, function):
    for i, v in enumerate(list):
        function(v, i, list)

You could also adapt this to map, reduce, filter, and any other array functions from other languages or precedence you’d want to bring over. For loops are fast enough, but the boiler plate is longer than forEach or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.


回答 4

尽管上面的答案是有效的,但是如果您要遍历字典{key:value},那么这是我喜欢使用的方法:

for key, value in Dictionary.items():
    print(key, value)

因此,如果我想对字典中的所有键和值进行字符串化处理,可以这样做:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

这样可以避免在应用这种类型的迭代时出现任何突变问题,而这可能会导致我的经验(有时)不稳定。

While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:

for key, value in Dictionary.items():
    print(key, value)

Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.


回答 5

对于一个字典,我们可以通过使用一个for循环迭代indexkey并且value

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##

For a dict we can use a for loop to iterate through the index, key and value:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##