24
19

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 5 years have passed since last update.

【Python】データ型とキャスト

Posted at

Pythonでファイルからデータを読み込んで比較演算子を使う場合、データ型とキャスト(変換)は重要というか意識しておいた方が良いです。
例えば、年齢と名前のカラムからなるCSVファイルがあったとします。

sample.csv
25,Taro
40,Hanako
30,Jiro

ここで、年齢が30歳以下の名前を取り出したくて、

test1.py
import csv

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        if row[0] <= 30:
            print(row[1])

と書いたとします。これを実行すると、

$ python test1.py 
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    if row[0] <= 30:
TypeError: '<=' not supported between instances of 'str' and 'int'

というエラーメッセージが表示されます。
内部ではrow[0]のデータ型がstr(文字列)と認識されている一方で、30のデータ型はint(数値)として認識されています。
そのため、データ型が異なるstrとintは比較ができませんよというエラーメッセージです。
そこで、

test2.py
import csv

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        if int(row[0]) <= 30: # row[0]をint型にキャストする
            print(row[1])

のようにrow[0]を明示的にintにキャストすると問題なく動きます。

$ python test2.py
Taro
Jiro

同じスクリプト言語でもPerlは内部で自動的にキャストしてくれるのですが、Pythonはそのような気の利いた事はやってくれません。
良い悪いは別として、Pythonで比較演算子を使う場合はデータ型とキャストを意識しておいた方が良いです。

24
19
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
24
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?