我潜入Python,我有一个关于每次迭代的问题。我是Python的新手,我有一些c#的经验。所以我想知道,在Python中是否有一些等效的函数用于迭代我的集合中的所有项目,例如。
pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或者像这样。
我潜入Python,我有一个关于每次迭代的问题。我是Python的新手,我有一些c#的经验。所以我想知道,在Python中是否有一些等效的函数用于迭代我的集合中的所有项目,例如。
pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或者像这样。
当前回答
对于更新的答案,您可以轻松地在Python中构建forEach函数:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
您还可以将其调整为map、reduce、filter以及来自其他语言的任何其他数组函数或您希望引入的优先级。For循环足够快,但锅炉板比forEach或其他功能长。您还可以扩展list,使这些函数具有指向类的局部指针,这样您也可以直接在列表上调用它们。
其他回答
是这样的:
for pet in pets :
print(pet)
事实上,Python只有foreach样式的for循环。
虽然上面的答案是有效的,如果你是在字典{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
在应用这种类型的迭代时,这避免了任何突变问题,在我的经验中,这可能会导致不稳定的行为(有时)。
不幸的是,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/
当然。一个for循环。
for f in pets:
print f
这招对我很管用:
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