我潜入Python,我有一个关于每次迭代的问题。我是Python的新手,我有一些c#的经验。所以我想知道,在Python中是否有一些等效的函数用于迭代我的集合中的所有项目,例如。

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

或者像这样。


当前回答

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

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

其他回答

当然。一个for循环。

for f in pets:
    print f

是这样的:

for pet in pets :
  print(pet)

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

对于更新的答案,您可以轻松地在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