2024-03-29 08:30:21 发布
网友
我正在深入研究Python,我有一个关于每个迭代的问题。我是Python新手,在C#方面有一些经验。所以我想知道,在Python中是否有一个等价的函数用于我的集合中所有项的迭代,例如
pets = ['cat', 'dog', 'fish'] marks = [ 5, 4, 3, 2, 1]
或者像这样的。
观察这个也很有趣
要遍历序列的索引,可以将range()和len()组合如下:
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()函数的时间。
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循环。
for
当然。一个for循环。
for f in pets: print f
观察这个也很有趣
要遍历序列的索引,可以将
range()
和len()
组合如下:输出
编辑1:备用方式:
当循环遍历一个序列时,位置索引和相应的值可以同时被检索 使用
enumerate()
函数的时间。输出
像这样:
实际上,Python只有具有foreach样式的
for
循环。当然。一个for循环。
相关问题 更多 >
编程相关推荐