Python-1

=====================================================================================

<< BACK >>

=====================================================================================

for

リスト,タプル

fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(fruit)

apple
banana
orange

辞書

scores = {'English': 90, 'Math': 80, 'Science': 70}
for subject, score in scores.items():
    print(f'{subject}: {score}')

English: 90
Math: 80
Science: 70

range関数

range(1, 10, 2): 1から9までの範囲の整数を2ずつ増加

for i in range(1, 10, 2):
    print(i)

1
3
5
7
9

breakとcontinue

breakは、任意の部分でループから抜け出す

for i in range(5):
    if i == 3:
        break
    print(i)

0
1
2

contiuneは残りの処理をスキップし、次のループを処理

for i in range(5):
    if i == 3:
        continue
    print(i)

0
1
2
4

<< BACK >>

=====================================================================================

文字列を抽出

半角文字も全角文字も同じ1文字としてカウントされる。

インデックス

[]にインデックスを指定。インデックスは1文字目が0。
s = 'abcde'
print(s[0])
# a
print(s[4])
# e

負の値:後ろからの位置指定。-1が最後尾。
print(s[-1])
# e
print(s[-5])
# a

スライス

[start:stop] → start <= x < stopの範囲の文字列を抽出。
startを省略すると先頭から、stopを省略すると末尾までの範囲となる
s = 'abcde'
print(s[1:3])
# bc
print(s[:3])
# abc
print(s[1:])
# bcde

負の値も使える。
print(s[-4:-2])
# bc
print(s[:-2])
# abc
print(s[-4:])
# bcde

[start:stop:step] → 開始位置startと終了位置stopに加えて、増分step。
stepに負の値を指定すると後ろから順番に抽出される。
print(s[1:4:2])
# bd
print(s[::2])
# ace
print(s[::3])
# ad
print(s[::-1])
# edcba
print(s[::-2])
# eca

<< BACK >>

=====================================================================================

f文字列

Python 3.6から導入された強力な機能。文字列内に直接Python式を埋め込みコードの可読性と効率を大幅に向上。

変数の値を文字列に挿入

name = "太郎"
age = 30
print(f"私の名前は{name}で、{age}歳です。")

実行結果:
私の名前は太郎で、30歳です。

 式の評価

x = 10
y = 20
print(f"{x} + {y} = {x + y}")

実行結果:
10 + 20 = 30

メソッドの呼び出し

name = "python"
print(f"大文字: {name.upper()}")

実行結果:
大文字: PYTHON

辞書のアクセス

person = {"name": "花子", "age": 25}
print(f"{person['name']}さんは{person['age']}歳です。")

実行結果:
花子さんは25歳です

条件式(三項演算子)

x = 15
print(f"{x}は{'偶数' if x % 2 == 0 else '奇数'}です。")

実行結果:
15は奇数です。

フォーマット指定子の使用

pi = 3.14159
print(f"円周率は{pi:.2f}です。")

実行結果:
円周率は3.14です

左寄せ、中央寄せ、右寄せ

name = "Python"
print(f"{name:<10}|")  # 左寄せ
print(f"{name:^10}|")  # 中央寄せ
print(f"{name:>10}|")  # 右寄せ

実行結果:
Python    |
  Python  |
    Python|

日付のフォーマット

from datetime import datetime
now = datetime.now()
print(f"現在時刻: {now:%Y-%m-%d %H:%M:%S}")

実行結果(実行時の日時により異なります):
現在時刻: 2024-07-28 12:34:56

2進数、8進数、16進数表現

num = 42
print(f"10進数: {num}")
print(f"2進数: {num:b}")
print(f"8進数: {num:o}")
print(f"16進数: {num:x}")

実行結果:
10進数: 42
2進数: 101010
8進数: 52
16進数: 2a

デバッグ用の=指定子

x = 10
y = 20
print(f"{x=}, {y=}")

実行結果:
x=10, y=20

<< BACK >>

=====================================================================================

 時刻取得

  • 基本的な日時取得 → datetime.now()
  • 時刻の計算や変換を楽にしたい → arrow
  • タイムゾーンを考慮したい → pytz
  • 処理時間計測 → timeit.default_timer() or time.perf_counter()
  • UNIXタイムが必要 → time.time()
用途適したライブラリ
現在の日時を取得 (ローカルタイム)datetime.datetime.now()
現在の時刻をエポック秒で取得time.time()
時刻を特定のフォーマットで表示time.localtime() + time.strftime()
タイムゾーンを考慮した時刻取得datetime.now(pytz.timezone(…)) or arrow.now()
WebAPIや時刻処理を簡単に扱いたいarrow.now()
時間計測 (コードの実行時間)timeit.default_timer() or time.perf_counter()

1. datetime.datetime.now()

用途・シチュエーション:

  • 一般的な日時取得: 日付や時刻を扱うシンプルな処理に最適.
  • フォーマットの自由度: .strftime() を使ってフォーマットを変更しやすい.
  • ローカル時刻の取得: datetime.now() はデフォルトでシステムのローカルタイムを取得する.

注意点:

  • タイムゾーン情報は含まれないため,グローバルな処理には pytz との併用が必要.
from datetime import datetime

# 現在の日時を取得
time_datetime= datetime.now()
print(time_datetime) 

# 2025-03-20 16:25:35.654095

2. time.time()

用途・シチュエーション:

  • エポック秒(Unix時間)の取得: 1970年1月1日からの経過秒数で時刻を扱いたいときに最適.
  • 時間差の計測: 2つの time.time() の差を取ることで処理時間を計測できる.

注意点:

  • 可読性が低いため,直接ユーザー向けに表示する用途には適さない.
import time

# 現在の時刻(エポック秒)を取得
time_time = time.time()
print(time_time)  
print(f"{time_time:.3f}")  # 小数点以下3桁まで表示

# 1742455535.6543741
# 1742455535.654

3. time.localtime() + time.strftime()

用途・シチュエーション:

  • ローカル時刻を文字列として扱う: strftime() によりフォーマットを簡単に変更できる.
  • ログ出力やUI表示: YYYY-MM-DD HH:MM:SS のような形に整えやすい.

注意点:

  • datetime に比べると直感的でない場合がある.
import time

# 現在の時刻をフォーマットして表示
local_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted_time)  

# 2025-03-20 16:25:35

4. datetime.now(pytz.timezone("Asia/Tokyo"))

用途・シチュエーション:

  • タイムゾーンを明示的に指定する必要がある場合: タイムゾーンが重要なアプリケーション(例: グローバル対応のWebサービス).
  • 異なるタイムゾーン間での時刻変換: pytz.timezone("UTC").localize(dt).astimezone(pytz.timezone("Asia/Tokyo")) などが可能.

注意点:

  • pytz は標準ライブラリではないため,pip install pytz が必要.
from datetime import datetime
import pytz

# タイムゾーンを指定して現在時刻を取得
time_pytz = pytz.timezone("Asia/Tokyo")
tokyo_time = datetime.now(time_pytz)
print(tokyo_time)  

# 2025-03-20 16:25:35.943172+09:00

5. arrow.now()

用途・シチュエーション:

  • datetime より直感的な時刻操作: .shift(days=1) で簡単に1日後の時刻を取得可能.
  • タイムゾーンを簡単に扱える: .to('Asia/Tokyo') で変換できる.
  • WebアプリやAPIでの時刻処理: ISO 8601 形式 (YYYY-MM-DDTHH:MM:SS+TZ) の出力が容易.

注意点:

  • arrow は標準ライブラリではなく,pip install arrow が必要.
import arrow

# 現在の時刻を取得
time_arrow= arrow.now()
print(time_arrow)  

# 2025-03-20T16:25:36.045942+09:00

6. timeit.default_timer()

用途・シチュエーション:

  • コードの実行時間計測: start = timeit.default_timer(); do_something(); elapsed = timeit.default_timer() - start
  • 高精度な時間測定: time.time() より精度が高い(環境によって異なる).

注意点:

  • datetime や time とは異なり,時刻取得の用途には適さない.
  • timeit.default_timer() は Windows では time.perf_counter(),Linux/macOS では time.monotonic() を内部的に使用する為,環境ごとに挙動が異なることがある.
import timeit

# 現在の時刻をエポック秒で取得
timestamp = timeit.default_timer()
print(timestamp)  

# 15251.0218552

 7. time.perf_counter()

用途・シチュエーション:

  • 高精度な時間計測: timeit.default_timer() 同様,処理時間の測定に適している.
  • システムの時計と無関係に動作: システムの時刻とは無関係に動作する為,プロセスの実行時間の測定等に適しており,精度が高い.

注意点:

  • 絶対的な時刻を取得するのではなく,相対時間の測定向け.

import time

# 高精度な時刻取得
current_time = time.perf_counter()
print(current_time)

# 15251.0220795

<< BACK >>

=====================================================================================

subprocess

外部処理をサブプロセスで行う。

subprocess.run()

  • subprocess.run([“ls”])
    • コマンドはリストで指定。
    • シェルで実行するようなコマンドが実行できるが出力を取得出来ない。
  • subprocess.run(“ls”,shell =True)
    • パイプ(|)、ワイルドカード(*)、環境変数展開、埋め込みコマンド(dir, cdなど)シェル機能が利用可能
    • コマンドはスペース区切りの文字列で渡します
  • 戻り値
    • proc = subprocess.run([“ls”],stdout = subprocess.PIPE, stderr = subprocess.PIPE)
      • print(proc.stdout.decode(“utf8”)) // python側で出力を取る。
    • cp = subprocess.run([‘ls’, ‘-a’])
      • cp.returncode -> OK:1 NG: Other

subprocess.Popen()

プロセスは並行に実行.起動したものが終了しているかどうかに関わらず,Popenの後に記述されたコードは実行
されます.

処理名       概要
Popen()プロセスの初期化、実行
Popen.wait()プロセスの終了を待機 
プロセス終了後、終了コード(リターンコード)を返す
Popen.poll()非同期的にプロセスの出力を取得
Popen.communicate()標準入力を渡し、標準出力と標準エラーを取得する
(stdout, stderr)プロセスの標準出力や標準エラーを取得

Popen.wait()

# 'sleep 2' コマンドを実行するプロセスを起動
process = subprocess.Popen(['sleep', '2'])
print("プロセスを開始しました。")

# プロセスが終了するまで待機
return_code = process.wait()

print(f"プロセスが終了しました。終了コード: {return_code}")

Popen.poll()

import subprocess
import time

# プロセスを開始 (終了を待たない)
process = subprocess.Popen(['sleep', '5']) # 例: 5秒待機するコマンド

print("プロセスを開始しました。")

# プロセスが終了するまでポーリングしつつ、他の処理を行う
while True:
    return_code = process.poll() # プロセスの状態をチェック
    if return_code is not None:
        print(f"プロセスが終了しました。終了コード: {return_code}")
        break
    else:
        print("プロセスはまだ実行中です...")
        time.sleep(1) # 1秒待ってから再度チェック

Popen.communicate()

import subprocess
import time

process = subprocess.Popen(
    ["grep", ".*\.txt"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
)

INPUT = "file_0.txt\nfile_1.txt\nfile_2.txt\nimg_1.jpg\nimg_2.jpg\nimg_3.jpg\n"

stdout, stderr = process.communicate(input=INPUT)
print("STDOUT:", stdout)
print("STDERR:", stderr)

<< BACK >>

=====================================================================================

リスト、タプル、辞書、集合

リスト [ ]

要素をカンマで区切って全体を大カッコ[]で囲む。
変更可。要素の挿入と削除を行うことができる。インデックス(番号)で要素にアクセス(読み書き)出来る。

List = ["A", "B", "C", "D", "E"]
print(List)  
# ⇒ ['A', 'B', 'C', 'D', 'E']

List = ["A", "B", "C", "D", "E"]
print(List[2])  
# ⇒ C

List = ["A", "B", "C", "D", "E"]
List[2]="Y"
List
# ⇒ ['A', 'B', 'Y', 'D', 'E']

タプル()

要素をカンマで区切って全体をカッコ()で囲む。->カッコ()無しでもOK
変更不可。インデックス(番号)で要素にアクセス(読み)出来る。

Tuple = ("A", "B", "C", "D", "E")
print(Tuple) 
# ⇒ ('A', 'B', 'C', 'D', 'E')

Tuple = ("A", "B", "C", "D", "E")
print(Tuple[2]) 
# ⇒ C

Tuple = ("A", "B", "C", "D", "E")
Tuple[2]="Y"
Tuple
# ⇒ Error  
# TypeError: 'tuple' object does not support item assignment

辞書 { }

key : valuのペアをカンマ区切って全体を中カッコ{ }で囲む。
変更可。リストに似ていますが要素へのアクセスはキーで行う。

Dictionary = {"USA":1, "JAPAN":2, "Germany":3}
Dictionary 
# ⇒ {'USA': 1, 'JAPAN': 2, 'Germany': 3}

Dictionary = {"USA":1, "JAPAN":2, "Germany":3}
Dictionary["JAPAN"] 
# ⇒ 2

集合 { }

set()関数を使うか、1個以上のカンマ区切りの値を波括弧で囲む。同じ要素を一つしか持てない。
変更可。要素へのアクセスはキーで行う。

SET = set(["USA","JAPAN","Germany","JAPAN"])
SET
# ⇒ {'Germany', 'JAPAN', 'USA'}

atomic = {'H','C','O','N'}
atomic
# ⇒ {'C', 'H', 'N', 'O'}

set("philadelphia") 
# ⇒ {'a', 'd', 'e', 'h', 'i', 'l', 'p'}

リストから集合を作る
US_list = ["Philadelphia","New York","LA","Boston","New York"]
set(US_list) 
# ⇒ {'Boston', 'LA', 'New York', 'Philadelphia'}

タプルから集合を作る
US_list2 = ("Philadelphia","New York","LA","Boston","New York")
set(US_list2) 
# ⇒ {'Boston', 'LA', 'New York', 'Philadelphia'}

辞書をset()で囲むとキーだけが使われる
atomic_weight = {'H': 1.008, 'C': 12.01, 'O': 16, 'N': 14.01}
set(atomic_weight) 
# ⇒ {'C', 'H', 'N', 'O'}

<< BACK >>

=====================================================================================

open()

open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

  • mode
    • 文字  意味
      'r'読み込み用に開く (デフォルト)
      'w'書き込み用に開き、まずファイルを切り詰める
      'x'排他的な生成に開き、ファイルが存在する場合は失敗する
      'a'書き込み用に開き、ファイルが存在する場合には末尾に追記する
      'b'バイナリモード
      't'テキストモード (デフォルト)
      '+'更新用に開く (読み込み・書き込み用)
  • buffering
    • 0: バッファリングを無効化 (バイナリモードでのみ設定可能です)
    • 1: 行単位でのバッファリング (テキストモードでの書き込み時のみ有効です)
    • >1: 固定サイズのチャンクバッファに対するサイズをバイト単位で指定
  • encoding
    • テキストモードでのみ使用
    • Pythonでサポートされているエンコーディングはどれでも使えます。
  • errors
    • エンコードやデコードでのエラーをどのように扱うかを指定
    • バイナリモードでは使用できません

ファイル全体を文字列として読み込み: read()
with open(path) as f:
s = f.read()

print(s)
# line 1
# line 2
# line 3

ファイル全体をリストとして読み込み: readlines()
with open(path) as f:
l = f.readlines()
print(l)
# [‘line 1\n’, ‘line 2\n’, ‘line 3’]

ファイルを一行ずつ読み込み: readline()
with open(path) as f:
for s_line in f:
print(repr(s_line))
# ‘line 1\n’
# ‘line 2\n’
# ‘line 3’

文字列を書き込み: write()
path_w = ‘data/temp/test_w.txt’

s = ‘New file’

with open(path_w, mode=‘w’) as f:
f.write(s)

with open(path_w) as f:
print(f.read())
# New file

リストを書き込み: writelines()
l = [‘One’, ‘Two’, ‘Three’]

with open(path_w, mode=‘w’) as f:
f.writelines(l)

with open(path_w) as f:
print(f.read())
# OneTwoThree

リストの要素ごとに改行して書き込む(+演算子、joinなど)
with open(path_w, mode=‘w’) as f:
f.write(‘\n’.join(l))

with open(path_w) as f:
print(f.read())
# One
# Two
# Three

<< BACK >>

=====================================================================================