Skip to content

#167 Python enumerate  #2

@LiuL0703

Description

@LiuL0703

它允许我们遍历数据并自动计数

for counter, value in enumerate(some_list):
    print(counter, value)
choices = ["first",'second','third','fourth','fifth']

#start为可选参数 默认从 0 开始
for index, item in enumerate(choices, start = 1):
    print index, item
#(1,"first")
#(2,"second")
#(3,"third")
#(4,"fourth")
#(5,"fifth")

#也可以这样表示
for index, item in enumerate(choices):
    print index + 1, item
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
    print(c, value)

# 输出:
(1, 'apple')
(2, 'banana')
(3, 'grapes')
(4, 'pear')

http://book.pythontips.com/en/latest/enumerate.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions