2014年5月26日月曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media; )のChapter 2(Sharing your Code: Modules of functions)、EXERCISE(p.55)を解いてみる。

EXERCISE(p.55)

コード(BBEdit)

sample55.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

"""
This is the 'nester.py' module and it provides one function called print_lol()
which prints lists that may or may not include nexted lists.

"""

def print_lol(the_list, indent=0):
    """
    This function takes a positional argument called 'the_list', which is any
    Python list (of ~ possibly _ nested lists). Each data item in the provided
    list is (recursively) printed to the screen on it's own line. 
    And takes a second argument (optional, default is 0) called 'indent', which
    is number(int). Any nested lists is indented this number of tab stops.
    """
    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item)
        else:
            for x in range(indent):
                print('\t', end='')
            print(each_item)

# おかしな出力結果になる。             

te.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import sample55

l = ['a', 'b', ['c', ['e', 'f']], [[['g', 'h', [['i', 'j', ['k', 'l']]]]]],
     'm', 'n']
     
sample55.print_lol(l)
print('*' * 30)
sample55.print_lol(l, 1)
print('*' * 30)
sample55.print_lol(l, 2)

入出力結果(Terminal)

$ ./test_sample55.py 
a
b
c
e
f
g
h
i
j
k
l
m
n
******************************
 a
 b
c
e
f
g
h
i
j
k
l
 m
 n
******************************
  a
  b
c
e
f
g
h
i
j
k
l
  m
  n
$

0 コメント:

コメントを投稿