问题:相当于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 ##

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