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

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

或者像这样。


当前回答

这招对我很管用:

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

其他回答

观察这一点也很有趣

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

是这样的:

for pet in pets :
  print(pet)

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

对于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

当然。一个for循环。

for f in pets:
    print f