我潜入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样式的for循环。

观察这一点也很有趣

要遍历一个序列的下标,你可以组合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

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

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

因此,如果我想做一些事情,比如stringify字典中的所有键和值,我会这样做:

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

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

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

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

您还可以将其调整为map、reduce、filter以及来自其他语言的任何其他数组函数或您希望引入的优先级。For循环足够快,但锅炉板比forEach或其他功能长。您还可以扩展list,使这些函数具有指向类的局部指针,这样您也可以直接在列表上调用它们。

对于dict,我们可以使用For循环遍历索引、键和值:

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

这招对我很管用:

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 can't do this..

但是python不支持。python中对这个和其他缺失函数特性的部分修复由各种第三方库提供,其中包括我帮助编写的一个库:参见https://pypi.org/project/infixpy/