Python構造化データ


通常、データは変数に格納されてプログラミングされます.
数値やテキストのようなデータはnumberやstringの形でデータが格納され、連続列を格納する際には配列と呼ばれるデータ構造が使用される.
配列には代表的なリスト、例があり、単純な線形代数の配列としてNumpyのendarrayを使用します.
次の形式のデータをどのように格納しますか?国際電話の国番号データを保存すれば
Country_PhoneNumber
- Korea : 82
- America : 01
- Swiss : 41
- Italy : 39
- Japan : 81
- China : 86
- Rusia : 07
...
上記のデータの中で、国番号を検索する最も簡単な方法は、用語で値を検索することです.
データ値を検索する場合、インデックスではなく「Korea」、「America」などのキーを使用してデータにアクセスするデータ構造をハッシュと呼ぶ.
HashはKeyとValueからなるデータ構造で、2列しかありませんが、行数が多いです.

ハッシュは他のプログラミング言語ではマッピング(mapping)、関連配列(associationarray)などと呼ばれ、Pythonではdictionary(dictionary)と呼ばれている.
Python文は中括弧{}を使用し、키(key) : 값(value)の形で表される.
# 파이썬 딕셔너리로 표현한 전화번호부
Country_PhoneNumber = {'Korea': 82, 'America': 1, 'Swiss': 41, 'Italy': 39, 'Japan': 81, 'China': 86, 'Rusia': 7}
Country_PhoneNumber['Korea']

ディクシャナを使用した例


ゲーム会社はファンタジーゲームの論理を作っている.

プレイヤーが宝箱を掘り出すときに、宝箱の中のアイテムやアイテムごとの相場を示す銀貨を作るプログラムを作るとしたら
  • アイテムを表示する関数
  • treasure_box = {'rope': 2, 'apple' : 10, 'torch' : 6, 'gold coin' : 50, 'knife' : 1, 'arrow' : 30}
    
    def display_stuff(treasure_box):
    	print("Congraturation!! you got a treasure box")
       	for k, v in treasure_box.items():
       		print("you have {} {}pcs".format(k, v))
            
    display_stuff(treasure_box)
  • 物品によって得る銀貨の関数
  • を表示する.
    coin_per_treasure = {'rope': 1, 'apple' : 2, 'torch' : 2, 'gold coin' : 5, 'knife' : 30, 'arrow' : 1}
    
    def total_silver(treasure_box, coin_per_treasure):
    	total_coin = 0
       	for treasure in treasure_box:
       		coin = coin_per_treasure[treasure] * treasure_box[treasure]
    		print("{}coins/pcs * {}pcs = {} coins".format(treasure, coin_per_treasure[treasure], treasure_box[treasure], coin))
            total_coin += coin
    	print('total_coin : ', total_coin)
    total_silver(treasure_box, coin_per_treasure)
    宝箱には、品物と数量、品物と価値(価値)がそれぞれバイナリ形式で格納され、同じ単語をキーとして各データ値に一致します.
    データを変数に格納することもできます.専制形式
    treasure_box = {'rope' : {'coin' : 1, 'pcs' : 2},
    		'apple' : {'coin' : 2, 'pcs' : 10},
    		'torch' : {'coin' : 2, 'pcs' : 6},
    		'gold coin' : {'coin' : 5, 'pcs' : 50},
    		'knife' : {'coin' : 30, 'pcs' : 1},
    		'arrow' : {'coin' : 1, 'pcs' : 30},
    		}
            
    treasure_box['rope']

    構造化データ


    上記のコードでは、bote boxに含まれる5つのデータは、coinおよびposの内部構造を有する.このようなデータ内部に自己構造を有するデータを構造化データと呼ぶ
    上記コード等のデータは表形式で展開される.bote boxデータは、5行(行)、2列(列)のデータになります.