0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

  • 研究など通してPythonをつかってきた上で便利だと思った表現を備忘録として残しておこうと思い書きました

リスト内法表記

代入しながら変数を用いる表現

  • セイウチ演算子 := を利用
  • := を利用したコードの書き換え例
    • 使用前

      str = input()
      if len(str) % 2 == 0:
          print('even')
      else:
          print('odd')
      

    • 使用後

      if len(str:=input()) % 2 == 0:
          print('even')
      else:
          print('odd')
      

代入と演算が1行で同時に実装できた

np.array

  • 行列計算が可能,表示がきれい

多次元リストとの比較

```python
import numpy as np
l = [[0, 1],[2,3]]
print(l)
np_l = np.array(l)
print(np_l)
```
<br>
  • 実行結果

    [[0, 1], [2, 3]]
    [[0 1]
     [2 3]]
    

クラス

  • 変数管理がしやすくなる
  • 既存のクラスを一部受け継いで改良することなども可能
  • 以下の例ではchessを1つのクラスとし,クラス内には盤面を管理する変数,盤面表示のメソッド,ナイトツアーの深さ優先探索を行うメソッドなどを定義

tqdm

  • 繰り返し処理などの時間がかかる処理でプログレス(進捗)をリアルタイムに表示してくれる

  • 以下の例では1回の実行に0.05秒かかる処理を100回繰り返す

    from tqdm import tqdm
    import time
    count_num = 100
    pbar = tqdm(range(count_num), desc="progress", postfix="postfix", ncols=80, total = count_num)
    for i in range(count_num):
        time.sleep(0.05)
        pbar.update(1)
    pbar.close()
    

  • 実行例

    progress:  16%|███                   | 16/100 [00:08<00:45,  1.85it/s, postfix]
    

色付きの標準出力

  • 出力のうち強調したい部分があるときに便利
  • 以下のナイトツアーの例では探索済みのマスには緑色で数字を入れ,未探索の部分には赤色で数字を入れる

標準出力の上書き

  • 出力する際に追加形式でprintするのではなく,上書き形式でprintしたいときもある

  • エスケープシーケンス \033[F\033[K を用いる

    • \033[F:1行カーソルを上に移動
    • \033[K:1行分消去
  • 以上を用いてn行分更新するための関数 clear_lines を定義

  • 以下ではprint文更新を用いてフラッシュ暗算を実装

  • + が移動していく簡単なアニメーションを作ってみる

    import time
    def clear_lines(n):
        for _ in range(n):
        print('\033[F\033[K', end = '')
    
    for i in range(100):
        for j in range(5):
            if i % j == 0:
                print('+')
            else:
                print('|')
        time.sleep(0.1)
        clear_lines(5)
    

  • 実行画面

  • 以下の画面から + が上から下に移動していく

    +
    |
    |
    |
    |
    
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?