Python 循环列表

星河私藏家

Python 循环列表

你可以使用Python的循环结构来遍历列表中的项目。遍历可以通过使用列表作为迭代器或使用索引来完成。

语法

Python列表提供了一个迭代器对象。要遍历一个列表,请使用以下for语句:

for obj in list:
   . . .
   . . .

示例1

看下面的例子 –

lst = [25, 12, 10, -21, 10, 100]
for num in lst:
   print (num, end = ' ')

输出

它将产生以下输出 输出

25 12 10 -21 10 100

示例2

要遍历列表中的项,请获取整数范围对象“0”到“len-1”。参见以下示例−

lst = [25, 12, 10, -21, 10, 100]
indices = range(len(lst))
for i in indices:
   print ("lst[{}]: ".format(i), lst[i])

输出

它将产生以下 输出

lst[0]: 25
lst[1]: 12
lst[2]: 10
lst[3]: -21
lst[4]: 10
lst[5]: 100

版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com

目录[+]

取消
微信二维码
微信二维码
支付宝二维码