LoginSignup
0

More than 5 years have passed since last update.

Python > string > AAA,BB,CCCC,DDD形式のそれぞれ語の文字数を表示する > for loop, 内包表記, map(len(), ), list(map()), lambda

Last updated at Posted at 2018-01-23
動作環境
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

string_counter_180123.py
# 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)

run
$ 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の記載があったため、追加しました。

string_counter_180123.py
# 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の場合。

run
$ 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の場合。

run
$ 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)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0