我正在学习Python,对于foreach迭代有一个问题。 我是Python的新手,但我有一些C#的经验。所以我想知道,Python中是否有一种等效的函数可以迭代遍历我的集合中的所有项,例如
pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
或者类似这样的东西。
当然,使用for循环。
for f in pets:
print f
就像这样:
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),使用本地指针指向一个类,以便在列表上直接调用这些函数。
虽然上面的回答都是有效的,但如果你要遍历一个字典 {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()
。 - Marc Maxmeisterstringified_dictionary.items()
对吧? - Matt对于一个字典,我们可以使用for循环来遍历index
、key
和value
:
dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
## Code here ##
foreach
结构不幸地不是集合本身的内在部分,而是外在的。结果有两个方面:
Python 不直接支持对集合的真正 foreach
。一个例子是:
myList.foreach( a => print(a)).map( lambda x: x*2) # python can't do this..
但是Python并不支持这个功能。有许多第三方库提供了对Python中一些遗漏的函数性特征的部分解决方案,其中包括我参与编写的一个库:请查看https://pypi.org/project/infixpy/
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 k,v in enumerate(pets):
等等。 - Hannuforeach
或链式操作。一个例子可能是myList.foreach(a => print(a)).map(lambda x: x*2)
。 - WestCoastProjects