相关疑难解决方法(0)

在'for'循环中访问索引?

如何访问索引本身以获取如下列表?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))
Run Code Online (Sandbox Code Playgroud)

当我使用循环遍历它时for,如何访问循环索引,在这种情况下从1到5?

python loops list

3312
推荐指数
22
解决办法
194万
查看次数

在Python FOR循环中获取循环计数

for循环遍历列表的Python 循环中,我们可以编写:

for item in list:
    print item
Run Code Online (Sandbox Code Playgroud)

它整齐地遍历列表中的所有元素.有没有办法在循环中知道到目前为止我循环了多少次?例如,我想要一个列表,在我处理了十个元素后,我想用它们做一些事情.

我想到的替代方案将是这样的:

count=0
for item in list:
    print item
    count +=1
    if count % 10 == 0:
        print 'did ten'
Run Code Online (Sandbox Code Playgroud)

要么:

for count in range(0,len(list)):
    print list[count]
    if count % 10 == 0:
        print 'did ten'
Run Code Online (Sandbox Code Playgroud)

到目前为止,是否有更好的方法(就像for item in list)获得迭代次数?

python for-loop

236
推荐指数
2
解决办法
30万
查看次数

标签 统计

python ×2

for-loop ×1

list ×1

loops ×1