【发布时间】:2017-03-13 18:59:08
【问题描述】:
我正在深入研究 Python,但我有一个关于 foreach 迭代的问题。我是 Python 新手,并且在 C# 方面有一些经验。所以我想知道,Python中是否有一些等效的函数可以对我的集合中的所有项目进行迭代,例如
pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或类似的东西。
【问题讨论】:
我正在深入研究 Python,但我有一个关于 foreach 迭代的问题。我是 Python 新手,并且在 C# 方面有一些经验。所以我想知道,Python中是否有一些等效的函数可以对我的集合中的所有项目进行迭代,例如
pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或类似的东西。
【问题讨论】:
当然。一个 for 循环。
for f in pets:
print f
【讨论】:
for k,v in enumerate(pets):等
foreach。或一般的链接。一个例子是``myList.foreach(a => print(a)).map(lambda x: x*2)`。
像这样:
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
【讨论】:
对于更新的答案,您可以轻松地在 Python 中构建 forEach 函数:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
您还可以将其调整为map、reduce、filter,以及您想要引入的其他语言或优先级的任何其他数组函数。 for 循环足够快,但样板比forEach 或其他函数长。您还可以扩展 list 以使这些函数具有指向类的本地指针,这样您也可以直接在列表上调用它们。
【讨论】:
虽然上面的答案是有效的,但如果你正在迭代一个 dict {key:value} 这是我喜欢使用的方法:
for key, value in Dictionary.items():
print(key, value)
因此,如果我想对字典中的所有键和值进行字符串化,我会这样做:
stringified_dictionary = {}
for key, value in Dictionary.items():
stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary
这可以避免在应用这种类型的迭代时出现任何突变问题,根据我的经验,这可能会导致不稳定的行为(有时)。
【讨论】:
copy,因此您可以在迭代期间操作字典(尽管您的副本将包含任何修改之前的所有键和值) -- 喜欢for key, value in Dictionary.copy().items()
不幸的是,foreach 构造不是集合固有的,而是集合外部的。结果是双重的:
Python 不支持直接在集合上使用真正的 foreach。一个例子是
myList.foreach( a => print(a)).map( lambda x: x*2)
但是python不支持。各种第三方库提供了对 python 中此功能和其他缺少的功能特性的部分修复,包括我帮助编写的一个库:参见 https://pypi.org/project/infixpy/
【讨论】:
对于 dict,我们可以使用 for 循环遍历 index、key 和 value:
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
【讨论】: