4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python: List(配列)要素の一括置換(辞書使用)

Posted at

非常に基本的なことですがPythonでList(配列)要素を一括置換したいときに、やり方に迷い時間をかけてしまうことが多いです。
単純なコードですが、ググって全然見つからなかったので記事にしておきます(見つけ方が悪いのでしょうが)。

subs = {1: '1 replaced', 
        2: '2 replaced'} 
ls = [0, 1, 2]
new_ls = [subs.get(element, element)  for element in ls]
print(new_ls)
結果
[0, '1 replaced', '2 replaced']

多分、もっと早い方法もあるのでしょうが、小さい配列ならこれで十分です。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?