Python操作におけるテクニカルな実装テクニック

Pythonの基礎実装に関する技術的ノウハウ

1. 文字列形式のリストを実リストに変換

astモジュールのliteral_eval関数を使用して文字列型リストを解析します。セキュリティリスクを回避するため、信頼できるデータのみ処理します。

import ast

input_str = '[[12, 33], [120, 33], [129, 0]]'
converted_list = ast.literal_eval(input_str)
print(converted_list)

2. 辞書内のリスト値を個別要素に分解

リスト型値を含む辞書を、インデックス付きキーに分解する処理:

original = {
    'bs_qr_code': 'A123',
    'ld_widget': 'F',
    'tkiness': [11, 12, 34]
}

processed = {}
for key, value in original.items():
    if isinstance(value, list):
        for idx, item in enumerate(value):
            new_key = f"{key}{idx+1}"
            processed[new_key] = item
    else:
        processed[key] = value

print(processed)

3. 文字列からブール型への変換

str_to_bool = lambda x: x == "True"

print(str_to_bool("False"))  # Falseを出力
print(str_to_bool("True"))   # Trueを出力

4. 16進数値のゼロ埋め処理

num = 11
# 2桁の16進数形式に変換
hex1 = format(num, '02x')  
hex2 = hex(num)[2:].zfill(2)

5. 浮動小数点精度制御

decimalモジュールを使用した高精度計算:

from decimal import Decimal, getcontext

getcontext().prec = 10
a = Decimal('1.15')
b = Decimal('2.35')
print(round(a, 1))  # 1.2
print(a + b)        # 3.50

6. 複数ADBコマンドの実行

import subprocess

device_id = "ap1234"
cmd = f"adb -s {device_id} shell"
process = subprocess.Popen(
    cmd.split(), 
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE
)

process.stdin.write(b"cd scripts\n")
process.stdin.write(b"./lamarr-pdmmic.sh\n")
process.stdin.write(b"exit\n")
process.stdin.flush()

7. バイトデータの文字列変換

raw_data = [b'\r\r\n0.00\r\r\n']
cleaned = raw_data[0].replace(b'\r\r\n', b'').decode()

8. ロギング用デコレータの実装

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Executing {func.__name__}")
        result = func(*args, **kwargs)
        print(f"Completed {func.__name__}")
        return result
    return wrapper

@log_decorator
def test_func():
    return "Operation Result"

9. C#ライブラリのPython統合

import clr
clr.AddReference(r"your_library.dll")
from Namespace import Class

10. キー存在検証付き辞書アクセス

data = {'snRFA': 12345}

try:
    value = data['mode']
except KeyError:
    print("Required key not found")

11. スレッド引数のアンパック処理

import threading

class CustomThread(threading.Thread):
    def __init__(self, target, args):
        super().__init__()
        self.target = target
        self.args = args

    def run(self):
        self.target(*self.args)

12. C++コードのPythonラッパー

Cythonを使用したC++統合手順:

  1. C++関数の宣言:example.cpp
  2. Cythonインターフェース:example.pyx
  3. ビルドスクリプト:setup.py
  4. Pythonでのインポート

13. ファイルロック管理

import portalocker

with open("data.txt", "r+") as f:
    portalocker.lock(f, portalocker.LOCK_EX)
    # ファイル操作
    portalocker.unlock(f)

14. オブジェクトのシリアライズ

import pickle

data = {"config": "value"}
with open("data.pkl", "wb") as f:
    pickle.dump(data, f)

with open("data.pkl", "rb") as f:
    loaded = pickle.load(f)

15. バージョン互換性の確認

TensorFlowのバージョンとPython互換性:

  • Python 3.7:TF 1.15.0まで対応
  • Python 2.7:TF 1.15.0まで対応

16. モジュール依存問題の解決

pip install package_name==compatible_version

17. 非同期処理の構文修正

async def async_func():
    await asyncio.sleep(1)

18. スレッド同期の代替策

ミューテックスやセマフォを使用した同期制御が推奨されます。

19. システムアーキテクチャの確認

import platform
print(platform.architecture())

20. クラスの文字列表現

class Device:
    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return self.name

タグ: Python データ変換 並列処理 例外処理 モジュール管理

7月3日 18:54 投稿