我潜入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]
或者像这样。
当前回答
不幸的是,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
不幸的是,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/
对于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
虽然上面的答案是有效的,如果你是在字典{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
在应用这种类型的迭代时,这避免了任何突变问题,在我的经验中,这可能会导致不稳定的行为(有时)。