Loop Techniques

2015.09.03 01:07

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>>
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with thezip() function.

>>>
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your {0}?  It is {1}.'.format(q, a)
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>>
>>> for i in reversed(xrange(1,10,2)):
...     print i
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>>
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f
...
apple
banana
orange
pear

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.

>>>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>>
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]



출처 : https://docs.python.org/2/tutorial/datastructures.html#tut-loopidioms

'List > Python' 카테고리의 다른 글

Loop Techniques  (0) 2015.09.03
Quick Sort  (0) 2015.06.18
import random  (0) 2015.06.17
Mail 보내기  (0) 2015.04.30
pattern생성 및 offset 확인  (0) 2015.03.31
string 모듈  (0) 2015.03.20

smleenull List/Python

티스토리 툴바