Python foreach 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40346498/
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 23:25:28  来源:igfitidea点击:

Python foreach equivalent

pythonforeach

提问by Bill

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.

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

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

or something like this.

或类似的东西。

回答by Hannu

Sure. A for loop.

当然。一个 for 循环。

for f in pets:
    print f

回答by Hyman Aidley

Like this:

像这样:

for pet in pets :
  print(pet)

In fact, Python onlyhas foreach style forloops.

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

回答by krishna

Its also interesting to observe this

观察这个也很有趣

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

要迭代序列的索引,您可以组合range()len()如下:

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:

编辑#1:替代方式:

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

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

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

output

输出

0 tic
1 tac
2 toe

回答by Robert Mennell

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

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

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

您还可以将其调整为mapreducefilter和来自其他语言的任何其他数组函数或您想要引入的优先级。For 循环足够快,但样板代码比forEach或 其他函数长。您还可以扩展列表以使用指向类的本地指针来拥有这些函数,这样您也可以直接在列表上调用它们。

回答by Marc Tanne

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

虽然上面的答案是有效的,但如果您在 dict {key:value} 上迭代,这就是我喜欢使用的方法:

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.

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

回答by Armaan Salam

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

对于字典,我们可以使用 for 循环遍历index,keyvalue

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