Python foreach等价物

2024-03-29 08:30:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在深入研究Python,我有一个关于每个迭代的问题。我是Python新手,在C#方面有一些经验。所以我想知道,在Python中是否有一个等价的函数用于我的集合中所有项的迭代,例如

pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]

或者像这样的。


Tags: 函数经验cat等价dogfish深入研究新手
3条回答

观察这个也很有趣

要遍历序列的索引,可以将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

像这样:

for pet in pets :
  print(pet)

实际上,Python只有具有foreach样式的for循环。

当然。一个for循环。

for f in pets:
    print f

相关问题 更多 >