Pythonノート(6)

8628 ワード

データ構造
 
一.概要
データ構造は基本的に、いくつかのデータを処理できる構造です.あるいは、関連するデータのセットを格納するために使用されます.
Pythonには、リスト、メタグループ、辞書の3つの組み込まれたデータ構造があります.それらをどのように使用するか、プログラミングを簡単にする方法を学びます.
 
二.リスト#リスト#
listは、順序付けされたプロジェクトのセットを処理するデータ構造です.つまり、リストにシーケンスを格納できるプロジェクトです.
リストを作成すると、リスト内のアイテムを追加、削除、または検索できます.アイテムを追加または削除できるため、リストは可変のデータ型であり、このタイプは変更できます.ある程度、配列と似ています.
例:
#!/usr/bin/python # Filename: using_list.py # This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] print 'I have', len(shoplist),'items to purchase.' print 'These items are:', # Notice the comma at end of the line for item in shoplist: print item, print '/nI also have to buy rice.' shoplist.append('rice') print 'My shopping list is now', shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0] olditem = shoplist[0] del shoplist[0] print 'I bought the', olditem print 'My shopping list is now', shoplist
 
出力:
 
$ python using_list.py I have 4 items to purchase. These items are: apple mango carrot banana I also have to buy rice. My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice'] I will sort my list now Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana', 'carrot', 'mango', 'rice']
 
三.メタグループ
メタグループとリストは非常に似ていますが、メタグループは文字列と同じように可変ではありません.つまり、メタグループを変更することはできません.メタグループは、カッコ内のカンマで区切られたアイテムによって定義されます.メタグループは、通常、文またはユーザ定義関数が安全に値のセットを採用できるようにするときに使用されます.すなわち、使用されるメタグループの値は変更されません.
 
四.辞書
辞書は、連絡先の名前で住所と連絡先の詳細を検索するアドレス帳に似ています.つまり、キー(名前)と値(詳細)を関連付けます.キーは一意でなければなりません.
 
辞書のキーとしては、文字列などの可変オブジェクトしか使用できませんが、辞書の値として可変または可変のオブジェクトを使用できます.基本的には、簡単なオブジェクトだけをキーとして使用するべきです.
キー値ペアは、辞書に次のようにマークされます.d = {key1 : value1, key2 : value2 } .キー/値ペアはコロンで分割され、各ペアはカンマで分割され、これらはすべてカッコに含まれます.
注意:辞書のキー/値ペアには順序がありません.特定の順序がほしい場合は、使用前に自分でソートする必要があります.
例:
 
#!/usr/bin/python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } print "Swaroop's address is %s"% ab['Swaroop'] # Adding a key/value pair ab['Guido'] = '[email protected]' # Deleting a key/value pair del ab['Spammer'] print '/nThere are %d contacts in the address-book/n' % len(ab) for name, address in ab.items(): print 'Contact %s at %s' % (name, address) if 'Guido' in ab: # OR ab.has_key('Guido') print "/nGuido's address is %s"% ab['Guido']
 
五.シーケンス#シーケンス#
リスト、メタグループ、文字列はシーケンスです.シーケンスの2つの主な特徴は、インデックスオペレータとスライスオペレータです.インデックスオペレータを使用すると、シーケンスから特定のアイテムをキャプチャできます.スライスオペレータを使用すると、シーケンスのスライス、すなわちシーケンスの一部を取得できます.
例:
#!/usr/bin/python # Filename: seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item 2 is', shoplist[2] print 'Item 3 is', shoplist[3] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name = 'swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:]
 
出力:
 
$ python seq.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Item 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'banana'] Item 1 to -1 is ['mango', 'carrot'] Item start to end is ['apple', 'mango', 'carrot', 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop  

, , 。 。 , 。

 

shoplist[1:3]は、位置1から始まり、位置2を含むが、位置3で停止したシーケンススライスを返し、2つの項目を含むスライスを返す.同様に、shoplist[:]はシーケンス全体のコピーを返す.
 
 
六.リファレンス
オブジェクトを作成して変数を割り当てると、この変数はオブジェクト自体を表すのではなく、そのオブジェクトのみを参照します.つまり、変数名は、そのオブジェクトをコンピュータに格納するメモリを指します.これは、オブジェクトへの名前のバインドと呼ばれます.
 
例:
#!/usr/bin/python # Filename: reference.py print 'Simple Assignment' shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print 'shoplist is', shoplist print 'mylist is', mylist # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print 'Copy by making a full slice' mylist = shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print 'shoplist is', shoplist print 'mylist is', mylist # notice that now the two lists are different
出力:
 
$ python reference.py Simple Assignment shoplist is ['mango', 'carrot', 'banana'] mylist is ['mango', 'carrot', 'banana'] Copy by making a full slice shoplist is ['mango', 'carrot', 'banana'] mylist is ['carrot', 'banana']
ある程度、Cのポインタに似ています.
 
 
七.文字列に関する補足
プログラムで使用する文字列はstrクラスのオブジェクトです.このクラスのいくつかの有用な方法は、次の例で説明します.これらのメソッドの完全なリストについては、help(str)を参照してください.
 
例:
 
#!/usr/bin/python # Filename: str_methods.py name = 'Swaroop' # This is a string object if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if name.find('war') != -1: print 'Yes, it contains the string "war"' delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print delimiter.join(mylist)
 
出力:
 
$ python str_methods.py Yes, the string starts with "Swa"Yes, it contains the string "a"Yes, it contains the string "war"Brazil_*_Russia_*_India_*_China
#!/usr/bin/python # Filename: using_tuple.py zoo = ('wolf', 'elephant', 'penguin') print 'Number of animals in the zoo is', len(zoo) new_zoo = ('monkey', 'dolphin', zoo) print 'Number of animals in the new zoo is', len(new_zoo) print 'All animals in new zoo are', new_zoo print 'Animals brought from old zoo are', new_zoo[2] print 'Last animal brought from old zoo is', new_zoo[2][2]
 
出力:
 
$ python using_tuple.py Number of animals in the zoo is 3 Number of animals in the new zoo is 3 All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin')) Animals brought from old zoo are ('wolf', 'elephant', 'penguin') Last animal brought from old zoo is penguin
変数zooはメタグループであり、len関数がメタグループの長さを取得するために使用できることを示した.これは、メタグループもシーケンスであることを示しています.
0個または1個のアイテムを含むメタグループ.1つの空の要素グループは、myempty = ()のような一対の空のカッコで構成される.しかし、単一の要素を含むメタグループはそれほど簡単ではありません.Pythonは、メタグループと式のカッコ付きオブジェクトを区別するために、最初の(唯一の)項目の後にカンマを付ける必要があります.すなわち、プロジェクト2を含むメタグループを望む場合は、singleton = (2 , )を示す必要があります.
 
例:
#!/usr/bin/python # Filename: print_tuple.py age = 22 name = 'Swaroop' print '%s is %d years old' % (name, age) print 'Why is %s playing with that python?' % name
 
出力:
 
$ python print_tuple.py Swaroop is 22 years old Why is Swaroop playing with that python?