SUPPORT UKRAINE
- Your indifference to the act of cruelty can thrive rogue nations like Russia -
タグ
            generator
 を含むブログ一覧
        【 Effective Python, 2nd Edition 】リストを返す関数を作るなら、ジェネレータを返しちゃダメか1回立ち止まって考えよう、の巻
                    Published 2020年6月27日19:16 by mootaro23
                
                
                    結果としてシーケンスを返す関数を作成する場合、最も一般的な選択肢は「リストを返す」ということでしょう。
次の例は、受け取った文字列について、文字列中の各単語の先頭インデックス番号と該当する単語のタプルからなるリストを返すものです。
sentence = "Nana is cute and very popular among my friends."
def index…
                
            【Python 雑談・雑学】 ループ処理でインデックス番号が使いたいのなら enumerate() を使えば?
                    Published 2020年5月26日21:45 by mootaro23
                
                
                    次のような処理をしています。
top_friends = ['Nana', 'Saki', 'Yuka']
print(f'My top 1 friend is {top_friends[0]}.')
print(f'My top 2 friend is {top_friends[1]}.')
print(f'My top 3 friend is {top_friends[2]}…
                
            Python Cookbook [Implementing the Iterator Protocol : イテレータープロトコルの実装]
                    Published 2020年5月9日9:29 by mootaro23
                
                
                    Problem:
イテレーションをサポートするカスタムオブジェクトを作成したいが、イテレータプロトコルの実装では苦労したくない。
Solution:
イテレーションをサポートするオブジェクトを作成する一番簡単な手段は generator 関数を利用することでしょう。
" Delegating Iteration " の項で取り上げたクラスを再利用してみます。
今回は Nod…
                
            Python Cookbook [Creating New Iteration Patterns with Generators : ジェネレーターを利用した独自イテレーションパターンの実装]
                    Published 2020年5月7日19:19 by mootaro23
                
                
                    Problem:
range() や reversed() といった組み込み関数とは異なるイテレーションパターンを実装したい。
Solution:
generator 関数を利用して実装します。
例えば、ある範囲内、あるステップ数で浮動小数点数を生成したいなら次のようになるでしょう。
def float_range(start, stop, step):
    …
                
            Python Cookbook [Finding the Date Range for the Current Month : その月は何日まで?]
                    Published 2020年4月18日18:17 by mootaro23
                
                
                    Problem:
ある月の全ての日を簡単にループ処理したい。
Solution:
対象となる月の日数分のリストを用意するような必要はありません。
開始日(その月の1日)と終了日(翌月の1日)を取得し、datetime.timedelta オブジェクトを利用してその間を1日ずつループしていきます。
from datetime import datetime, date, ti…
                
            