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?

sympyの小技:辞書を1行にする方法(※この記事はAIで書かれています)

0
Last updated at Posted at 2026-08-24
Sympyで1行にするおすすめの方法を教えてください。
r_sol =solve(Eq(C.y,4),r)[0]   
rep ={r:r_sol}

1. 【一番おすすめ】 dict=True オプションを使う

# solveのdict=Trueオプションを利用して1行で辞書を作成する
rep = solve(Eq(C.y, 4), r, dict=True)[0]

2. 【シンプル】 直接辞書を作成する

# そのまま直接辞書の形式にまとめる
rep = {r: solve(Eq(C.y, 4), r)[0]}

3. 【応用】 代入(.subs)が目的の場合

# 式 expr の変数 r に解を直接代入する
result = expr.subs(solve(Eq(C.y, 4), r, dict=True)[0])
Eq(C.y, 4) の解が複数ある場合の処理や、安全な解の取り出し方について教えてください。

1. 変数(Symbol)に前提条件(Assumptions)を与える

# 変数定義時に正の実数(positive=True)の制約を付与する
from sympy import Symbol, Eq, solve

r = Symbol('r', positive=True) # 実数かつ正の値のみに限定
sols = solve(Eq(C.y, 4), r, dict=True)

# 制約を満たす解のみが返されるため、safeに取得可能
rep = sols[0] if sols else {}

2. 三項演算子で IndexError を防止する

# 解が存在する場合のみ最初の解を取り出し、なければ空の辞書を返す
sols = solve(Eq(C.y, 4), r, dict=True)
rep = sols[0] if sols else {}

3. リスト内包表記で条件に合う解だけをフィルタリングする

# 得られた解の中から実数(is_real)のものだけを抽出する
sols = solve(Eq(C.y, 4), r, dict=True)
real_sols = [s for s in sols if s[r].is_real]

rep = real_sols[0] if real_sols else {}

4. モダンな標準関数 solveset を使用する

# solvesetを使って実数域(S.Reals)の解集合を取得する
from sympy import solveset, S, Eq

sol_set = solveset(Eq(C.y, 4), r, domain=S.Reals)

# 集合から要素を取り出して辞書化(解が存在する場合)
rep = {r: list(sol_set)[0]} if sol_set else {}
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?