# 在列表理解中使用枚举的Python

``mylist = ["a","b","c","d"]` `

` `>>> for i,j in enumerate(mylist): ... print i,j ... 0 a 1 b 2 c 3 d >>>` `

` `>>> [i,j for i,j in enumerate(mylist)] File "<stdin>", line 1 [i,j for i,j in enumerate(mylist)] ^ SyntaxError: invalid syntax` `

` `[(i, j) for i, j in enumerate(mylist)]` `

` `[pair for pair in enumerate(mylist)]` `

` `> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]` `

` `[(i,j) for i in range(3) for j in 'abc']` `

` `[{i:j} for i in range(3) for j in 'abc']` `

` `[[i,j] for i in range(3) for j in 'abc']` `

` `[i,j for i in range(3) for j in 'abc']` `

` `>>> {i:j for i,j in enumerate('abcdef')} {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}` `

` `>>> {(i,j) for i,j in enumerate('abcdef')} set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])` `

` `>>> [t for t in enumerate('abcdef') ] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]` `

` `>>> mylist = ["a","b","c","d"] >>> list(enumerate(mylist)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]` `

` `~\$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))" 1000000 loops, best of 3: 1.61 usec per loop ~\$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]" 1000000 loops, best of 3: 0.978 usec per loop ~\$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]" 1000000 loops, best of 3: 0.767 usec per loop` `

` `>>> mylist = ['a', 'b', 'c', 'd'] >>> [item for item in enumerate(mylist)] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]` `

` `>>> [(i, j) for i, j in enumerate(mylist)] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]` `

` `[(i, j) for (i, j) in enumerate(mylist)]` `

` `from itertools import izip, count a = ["5", "6", "1", "2"] tupleList = list( izip( count(), a ) ) print(tupleList)` `

` `a = ["5", "6", "1", "2"] b = ["a", "b", "c", "d"] tupleList = list( izip( count(), a, b ) ) print(tupleList)` `