Python-foreach等价物

Python-foreach等价物,python,foreach,Python,Foreach,我正在深入研究Python,我对每次迭代都有一个问题。我是Python新手,对C#有一些经验。所以我想知道,在Python中是否有一些等价的函数用于迭代我集合中的所有项,例如 pets = ['cat', 'dog', 'fish'] marks = [ 5, 4, 3, 2, 1] 或者类似的事情 当然。一个for循环 for f in pets: print f 像这样: for pet in pets : print(pet) 事实上,Python只有foreach样式的

我正在深入研究Python,我对每次迭代都有一个问题。我是Python新手,对C#有一些经验。所以我想知道,在Python中是否有一些等价的函数用于迭代我集合中的所有项,例如

pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或者类似的事情

当然。一个for循环

for f in pets:
    print f
像这样:

for pet in pets :
  print(pet)

事实上,Python只有foreach样式的
用于
循环。

观察这一点也很有趣

要迭代序列的索引,可以按如下方式组合
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

虽然上面的答案是有效的,但如果您在dict{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

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

要获得更新的答案,您可以轻松地在Python中构建
forEach
函数:

def forEach(列表,函数):
对于枚举中的i、v(列表):
功能(v、i、列表)

您还可以将其调整为
map
reduce
filter
,以及来自其他语言的任何其他数组函数或您希望采用的优先级。For循环足够快,但锅炉板比forEach
或其他函数长。您还可以扩展list,使其具有指向类的本地指针,以便您也可以直接在list上调用这些函数。

对于dict,我们可以使用For循环来迭代
索引

这对我很有用:

def smallest_missing_positive_integer(A):
A.sort()
N = len(A)

now = A[0]
for i in range(1, N, 1):
  next = A[i]
  
  #check if there is no gap between 2 numbers and if positive
  # "now + 1" is the "gap"
  if (next > now + 1):
    if now + 1 > 0:
      return now + 1 #return the gap
  now = next
    
return max(1, A[N-1] + 1) #if there is no positive number returns 1, otherwise the end of A+1

不幸的是,
foreach
构造不是集合固有的,而是集合外部的。结果有两个方面:

  • 它不能用链子拴住
  • 它需要两行惯用python代码
Python不支持直接在集合上使用true
foreach
。例如

myList.foreach( a => print(a)).map( lambda x:  x*2)

但是python不支持它。各种第三方库(包括我帮助编写的库)提供了对python中此功能和其他缺失功能的部分修复:请参见

如果我还必须知道索引/键,该怎么办?然后您将使用enumerate<代码>用于枚举(pets)中的k,v:
等。不幸的是,此构造不是集合的固有结构,而是集合的外部结构。结果有两个方面:(1)它不能被链接(2)在惯用python中需要两行代码。Python不支持直接在集合上使用true
foreach
。或者说,一般来说是用链子拴起来的。例如``myList.foreach(a=>print(a)).map(lambda x:x*2)`。一个更可读的替代方法是迭代字典的
副本
,这样您就可以在迭代过程中操作字典(尽管在任何修改之前,您的副本将是所有键和值的副本)--如
for key,Dictionary.copy().items()中的值。
您能包括用法吗?
myList.foreach( a => print(a)).map( lambda x:  x*2)