LoginSignup
2
1

More than 5 years have passed since last update.

複数のlist内のアイテムを一括で置換したい時

Posted at
print(AA, BB, CC)
>>> [0, 1, 2, 3, None, 5, 6, 7, 8, 9] ['q', 'w', 'e', None, 't', 'y'] [True, True, False, False, None]

という3つのリストがあるとする。
このときのNoneを'replace'に置換したい。

LL = [AA, BB, CC]
for L1 in LL:
    L1 = [x if x != None else 'replace' for x in L1]
print(LL)

>>> [[0, 1, 2, 3, None, 5, 6, 7, 8, 9], ['q', 'w', 'e', None, 't', 'y'], [True, True, False, False, None]]

置換されない。
そこで,こうする。

LL = [AA, BB, CC]
for i in range(len(LL)):
    LL[i] = [x if x != None else 'replace' for x in LL[i]]
print(LL)
>>> [[0, 1, 2, 3, 'replace', 5, 6, 7, 8, 9], ['q', 'w', 'e', 'replace', 't', 'y'], [True, True, False, False, 'replace']]

こうすると置換される。
最後にもとに戻してあげればよい。

AA, BB, CC = LL
print(AA, BB, CC)
>>> [0, 1, 2, 3, 'replace', 5, 6, 7, 8, 9] ['q', 'w', 'e', 'replace', 't', 'y'] [True, True, False, False, 'replace']
2
1
3

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