CentOS 6.8 (64bit)
Python 2.6.6 for code v0.1, v0.2
Python 3.4.5 for code v0.2
処理概要
以下の形式の文字列が与えられる。
IN_TXT = "3.141592,2.817,6.022,1023"
それぞれの語の文字数を表示する。
code v0.1
# on Python 2.6.6
# on Python 3.4.5
def count_word_length_forloop(atxt):
for elem in atxt.split(','):
print(len(elem))
def count_word_length_comprephension(atxt):
print([len(elem) for elem in atxt.split(',')])
IN_TXT = "3.141592,2.817,6.022,1023"
count_word_length_forloop(IN_TXT)
count_word_length_comprephension(IN_TXT)
$ python string_counter_180123.py
8
5
5
4
[8, 5, 5, 4]
備考
「内包表記」という用語を思い出せなかった。僕自身があまり使わないからだろうか。
内表表記の表示は項目数が多いときに見やすそう。for loopでも頑張れば見やすい表記はできるだろうが。
検索用キーワード
- List comprehension
link
@shiracamus さん
内包表記には、リスト内包表記、辞書内方表記、ジェネレータ内包表記があります。
このあたりはまだ覚えてませんでした。。。
code v0.2
@shiracamus さんのコメントにて教えていただきました関数2つを掲載しました。
情報感謝です。
Python3ではPython2用コードは実行しないようにしていますが、将来の参照用として。
https://docs.python.jp/3/tutorial/datastructures.html#list-comprehensions
にてlambdaの記載があったため、追加しました。
# on Python 2.6.6
# on Python 3.4.5
import sys
def count_word_length_forloop(atxt):
for elem in atxt.split(','):
print(len(elem))
def count_word_length_comprephension(atxt):
print([len(elem) for elem in atxt.split(',')])
def count_word_length_map_len(atxt):
if sys.version[0] != "2":
print("not for Python3")
return
print(map(len, atxt.split(',')))
def count_word_length_list_map(atxt):
print(list(map(len, atxt.split(','))))
def count_word_length_lambda(atxt):
print(list(map(lambda x: len(x), atxt.split(','))))
IN_TXT = "3.141592,2.817,6.022,1023"
count_word_length_forloop(IN_TXT)
count_word_length_comprephension(IN_TXT)
count_word_length_map_len(IN_TXT)
count_word_length_list_map(IN_TXT)
print('---')
count_word_length_lambda(IN_TXT)
Python2の場合。
$ python2 string_counter_180123.py
8
5
5
4
[8, 5, 5, 4]
[8, 5, 5, 4]
[8, 5, 5, 4]
---
[8, 5, 5, 4]
Python3の場合。
$ python3 string_counter_180123.py
8
5
5
4
[8, 5, 5, 4]
not for Python3
[8, 5, 5, 4]
---
[8, 5, 5, 4]
list, map, lambdaはまだ記憶だけではコーディングできません。精進いたします。
(Pythonista in the making)
- map
- https://docs.python.jp/3/library/functions.html#map
-
function を、結果を返しながら iterable の全ての要素に適用するイテレータを返します。
- list
- https://docs.python.jp/3/library/functions.html#func-list
-
list は、実際には関数ではなくミュータブルなシーケンス型で、 リスト型 (list) と シーケンス型 — list, tuple, range にドキュメント化されています。