bionote.net

[Python] Looping Techniques


When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.
[CODE]>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.iteritems(): ... print k, v ... gallahad the pure robin the brave[/CODE]

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
[CODE]>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe[/CODE]

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
[CODE]>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your %s? It is %s.' % (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.[/CODE]

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
[CODE]>>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1[/CODE]

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
[CODE]>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print f ... apple banana orange pear[/CODE]

PythonTutorial
2005/05/06 15:37 2005/05/06 15:37
top

TRACKBACK ADDRESS :: http://bionote.net/tt/blna999/trackback/26

  1. Tracked from 찬석의블로그 2005/05/06 15:57 DELETE

    Subject: [Python] file로 읽은 것 한줄씩 루프처리하기

    file handle로 받지 않고 sequence로 바로 저장해서 사용한다. [CODE]db = open("file.txt",'r').readlines() for line in db: print line[/CODE]

Leave a comment..