Python学習ノート(7):データ構造

5609 ワード

Pythonには、リスト、メタグループ、辞書の3つのデータ構造があります.
1.リスト(List)
リストは相手カッコ[]で表され、各データ間はカンマで区切られています.リストを作成すると、追加、削除、または検索できます.だからリストは変えることができます.
1)リストの作成
shoplist = ["apple", "mango", "carrot", "banana"]

print("I have", len(shoplist), "items to purchase.")


2)遍歴
for item in shoplist:

    print(item)


3)データの追加
print("I also have to buy rice.")

shoplist.append("rice")

print("My shopping list is now", shoplist)


4)並べ替え
shoplist.sort()

print("Sorted shopping list is", shoplist)


5)検索
print("The first item I will buy is", shoplist[0])


6)データの削除
olditem = shoplist[0]

del shoplist[0]

print("I bought the", olditem)

print("My shopping list is now", shoplist)


2.タプル
メタグループとリストは非常に似ていますが、メタグループは変更できません.つまり、変更できません.メタグループは、1対のカッコ()で表され、各データ間もカンマで区切られます.メタグループは、通常、文またはユーザ定義関数が安全に値のセットを採用できるようにするときに使用されます.すなわち、使用されるメタグループの値は変更されません.
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])


メタグループには、リストと同じインデックス演算子があります.0個または1個のアイテムを含むメタグループ.空のメタグループは、myempty=()などの一対の空のカッコで構成されます.しかし、単一の要素を含むメタグループはそれほど簡単ではありません.Pythonは、メタグループと式のカッコ付きオブジェクトを区別するために、最初の(唯一の)項目の後にカンマを付ける必要があります.すなわち、プロジェクト2を含むメタグループを望む場合は、singleton=(2,)を指定する必要があります.
メタグループの最も一般的な使い方は、印刷文で使用されます.
age = 22

name = "Swaroop"

print("%s is %d years old" % (name, age))

print("Why is %s playing with that python?" % name)


%sは文字列を表し、%dは整数を表す.
3.辞書(dict)
辞書はキー値ペアの集合であり、キーは一意でなければなりません.辞書のキーとしては、文字列などの可変オブジェクトしか使用できませんが、可変または可変のオブジェクトを辞書の値として使用できます.辞書は、各キー値ペア間をカンマで区切り、キー値間をコロンで区切ります.
1)辞書の作成
ab = {"user1" : "[email protected]", "user2" : "[email protected]"}


2)遍歴
for name, address in ab.items():

    print("Contact %s at %s" % (name, address))


3)データの追加
if not "tom" in ab:#OR not ab.has_key("tom")

    ab["Tom"] = "[email protected]"


4)検索
print("user1's address is %s" % ab["user1"])

5)削除
del ab["tom"]


4.シーケンス
リスト、メタグループ、文字列はシーケンスであり、シーケンスの2つの主な特徴はインデックスオペレータとスライスオペレータです.インデックスオペレータを使用すると、シーケンスから特定のアイテムをキャプチャできます.スライスオペレータを使用すると、シーケンスのスライス、すなわちシーケンスの一部を取得できます.
#Indexing or "Subscription" operation

print("Item 0 is", shoplist[0])

print("Item -1 is", shoplist[-1])



#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 = "known"

print("charactor 1 to 3 is", name[1:3])


インデックスは同じように負数でもよいが,その場合,位置はシーケンスの最後から計算される.したがって、shoplist[-1]はシーケンスの最後の要素を表し、shoplist[-2]はシーケンスの最後から2番目の項目をキャプチャする.
スライスオペレータは、シーケンス名の後に四角カッコ、四角カッコにオプションの数字のペアがあり、コロンで分割されます.これは、使用するインデックスオペレータとよく似ています.数はオプションで、コロンは必須です.[スライス](Slice)オペレータの最初の数(コロンの前)はスライスの開始位置を示し、2番目の数(コロンの後)はスライスがどこで終了するかを示します.最初の数を指定しないと、Pythonはシーケンスの先頭から始まります.2番目の数が指定されていない場合、Pythonはシーケンスの最後に停止します.なお、返されるシーケンスは、開始位置から始まり、終了位置の直前に終了する.すなわち、開始位置はシーケンススライスに含まれ、終了位置はスライスの外に排斥される.
5.オブジェクトと参照
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


出力結果:
Simple Assignmentshoplist is ["mango", "carrot", "banana"]mylist is ["mango", "carrot", "banana"]Copy by making a full sliceshoplist is ["mango", "carrot", "banana"]mylist is ["carrot", "banana"]
6.文字列関数
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))


出力結果:
Yes, the string starts with 'Swa'Yes, it contains the string 'a'Yes, it contains the string 'war'Brazil_*_Russia_*_India_*_China