LoginSignup
48
33

More than 5 years have passed since last update.

リストの空の要素を駆逐する

Last updated at Posted at 2019-03-20

更新履歴: 間違いを修正しました。@shiracamusさん、ありがとうございます。

Introduction

あるデータを読み込むと、以下のようなリストが返されました。

>>> list_example = ['a', '', '', 'b', 'c', '']

この空の要素''をサクッと取り除くためにはどうすればよいでしょうか。

removeメソッド

removeメソッド

試しにremoveメソッドを使って、空の要素を取り除いてみます。

>>> list_example.remove('')
>>> list_example
['a', '', 'b', 'c', '']

'a'の隣の空の要素が一つ削除されていることがわかります。このように、removeメソッドはリストの先頭から検索して最初に発見した該当要素を削除します。

空の要素がn個あった場合に、それらを全部駆逐したければ、removeメソッドをn回繰り返せばよい、ということになります。

removeメソッドの戻り値は何か

>>> list_example = ['a', '', '', 'b', 'c', '']
>>> type(list_example.remove(''))
<class 'NoneType'>

余談ですが、実はremoveメソッドの処理が成功した場合はNoneを返します(つまり何も返しません)。となるとこのメソッドの戻り値を頼りに、forやwhileでTrueの場合には削除を続ける(Falseで削除を終了する)なんて操作はできなさそうですね。

また、removeメソッドは該当する要素が見つからない時には以下のような例外を返します。

>>> list_example.remove('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

whileループで空の要素を駆逐する

以下のように、whileループの中のif文の条件式に要素を指定することで、空の要素を取り除くことができます。

>>> count = 0
>>> list_example2 = []
>>> while count < len(list_example):
...     if list_example[count] != '':
...         list_example2.append(list_example[count])
...     count += 1
... 
>>> list_example2
['a', 'b', 'c']

forループで空の要素を駆逐する

また上述のスクリプトはforループで書くことも可能です。

>>> list_example3 = []
>>> for a in list_example:
...     if a != '':
...         list_example3.append(a)
... 
>>> list_example3
['a', 'b', 'c']

内包表記で空の要素を駆逐する

上2つのようにwhile文, for文を使う方法もありますが、スクリプトが長くなってしまいます。そんな時には、Pythonでおなじみの内包表記が便利です。

>>> list_example4 = [a for a in list_example if a != '']
>>> list_example4
['a', 'b', 'c']

filter関数とlambda(無名関数)で空の要素を駆逐する

>>> list_example5 = filter(lambda a: a != '', list_example)
>>> list_example5
<filter object at 0x1102e64e0>
>>> list(list_example5)
['a', 'b', 'c']

Python3系では、filter関数filterオブジェクトを返します。リストとして取得したい場合にはlist関数を使いましょう。

参考Link:
https://teratail.com/questions/92477
https://it-engineer-lab.com/archives/124

48
33
2

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
48
33