# loop - python print list

## 在'for'循環中訪問索引? (14)

``````ints = [8, 23, 45, 12, 78]
``````

# 使用for循環，如何訪問循環索引，在這種情況下從1到5？

``````for index, item in enumerate(items):
print(index, item)
``````

``````for count, item in enumerate(items, start=1):
print(count, item)
``````

# Unidiomatic控制流程

``````index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop
print(index, item)
index += 1
``````

``````index = 0
while index < len(items):
print(index, items[index])
index += 1
``````

``````for index in range(len(items)):
print(index, items[index])
``````

# 使用枚舉函數

Python的`enumerate`函數通過隱藏索引的會計，並將iterable封裝到另一個迭代（ `enumerate`對象）中來減少視覺混亂，該迭代產生索引的兩項元組和原始迭代將提供的項。 看起來像這樣：

``````for index, item in enumerate(items, start=0):   # default is zero
print(index, item)
``````

## 算一算

``````for count, item in enumerate(items, start=1):   # default is zero
print(item)

print('there were {0} items printed'.format(count))
``````

## 打破它 - 一步一步的解釋

``````items = ['a', 'b', 'c', 'd', 'e']
``````

``````enumerate_object = enumerate(items) # the enumerate object
``````

``````iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)
``````

``````(0, 'a')
``````

``````index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.
``````

``````>>> print(index)
0
>>> print(item)
a
``````

# 結論

• Python索引從零開始
• 要在迭代時從迭代中獲取這些索引，請使用枚舉函數
• 以慣用的方式使用枚舉（以及元組解包）創建更易讀和可維護的代碼：

``````for index, item in enumerate(items, start=0):   # Python indexes start at zero
print(index, item)
``````

``````data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
a = (i, str(item).split('.'))
x.append(a)
for index, value in x:
print(index, value)
``````

``````0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']
``````

``````for idx, val in enumerate(ints):
print(idx, val)
``````

Python 2.7中訪問循環內列表索引的最快方法是對小型列表使用range方法 ，對中型和大型列表使用枚舉方法

``````from timeit import timeit

# Using range
def range_loop(iterable):
for i in range(len(iterable)):
1 + iterable[i]

# Using xrange
def xrange_loop(iterable):
for i in xrange(len(iterable)):
1 + iterable[i]

# Using enumerate
def enumerate_loop(iterable):
for i, val in enumerate(iterable):
1 + val

# Manual indexing
def manual_indexing_loop(iterable):
index = 0
for item in iterable:
1 + item
index += 1
``````

``````from timeit import timeit

def measure(l, number=10000):
print "Measure speed for list with %d items" % len(l)
print "xrange: ", timeit(lambda :xrange_loop(l), number=number)
print "range: ", timeit(lambda :range_loop(l), number=number)
print "enumerate: ", timeit(lambda :enumerate_loop(l), number=number)
print "manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number)

measure(range(1000))
# Measure speed for list with 1000 items
# xrange:  0.758321046829
# range:  0.701184988022
# enumerate:  0.724966049194
# manual_indexing:  0.894635915756

measure(range(10000))
# Measure speed for list with 100000 items
# xrange:  81.4756360054
# range:  75.0172479153
# enumerate:  74.687623024
# manual_indexing:  91.6308541298

measure(range(10000000), number=100)
# Measure speed for list with 10000000 items
# xrange:  82.267786026
# range:  84.0493988991
# enumerate:  78.0344707966
# manual_indexing:  95.0491430759
``````

``````for i in ints:
indx=ints.index(i)
print(i,indx)
``````

``````for counter, value in enumerate(ints):
print(counter, value)
``````

``````for counter in range(len(ints)):
print(counter,ints[counter])
``````

``````for i, num in enumerate(nums, start = 1):
print(i, num)
``````

``````for i, num in range(1, l + 1):
print(i, nums[i])
``````

``````ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]
``````

``````ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]
``````

``````ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]
``````

``````ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
index +=1
print index, value
``````

``````ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
index +=1
print index, value
if index >= len(ints)-1:
index = 0
``````

``````int_list = [8, 23, 45, 12, 78]
for index, value in enumerate(int_list):
print(index, value)
``````

``````0 8
1 23
2 45
3 12
4 78
``````

``````for i in range(len(sequence)):
# work with index i
``````

``````for i in range(len(sequence)):
e = sequence[i]
# work with index i and element e
``````

``````for i, e in zip(range(len(sequence)), sequence):
# work with index i and element e
``````

``````for ix in range(len(ints)):
print ints[ix]
``````

``````[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
...
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print tup
...
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>>
``````

``````In [1]: ints = [8, 23, 45, 12, 78]

In [2]: for idx, val in enumerate(ints):
...:         print(idx, val)
...:
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
``````

``````for x in range(0, 5):
``````

``````list[index]
``````

``````for i in range(len(ints)):
print i, ints[i]
``````