mdr141
10/23/2018 - 12:48 PM

Pyコレクション型

List, Tuple, Set, Dictionary

# Sequence
s = "HELLO"
print(s[1]) # E
print(s[-1]) # O
# Dictionary {key1:value1, key2:value2, key3:value3, ...} ※要素の重複不可
colors = {"red":"赤", "green":"緑", "blue":"青", "blue":"青"}
print(colors)
"""
{'red': '赤', 'green': '緑', 'blue': '青'}
"""

# 要素数を取得
print(len(colors))

# 指定キーの値を取得
print(colors["green"])

# 指定キーの値を変更
colors["blue"] = "青色"
print(colors)

# 指定キーを検索
print("red" in colors)
print("yellow" in colors)

# ペア追加
colors["alpha"] = "アルファ"
print(colors)

# ペア削除
del colors["alpha"]
print(colors)

# 全キー取得
print(colors.keys())
# 全値取得
print(colors.values())
# 全ペア取得
print(colors.items())
# for文で一覧表示
for eng, jap in colors.items():
	print("{}: {}".format(eng, jap))

# キーをリストに変換する(値も同様に可能)
# colorsの全キーを、dict1に代入
dict1 = colors.keys()
print(type(dict1))
# dict1をlist()コンストラクタでリストに変換し、list1に代入
list1 = list(dict1)
print(list1)
print(type(list1))
# Set ※要素の重複不可
color = {"R", "G", "B", "G",}
print(color)


# Setのいろいろな操作
c = {"R", "G", "B"}
print(c)

# 要素追加
c.add("A")
print(c)

# 重複要素は追加されない
c.add("R")
print(c)

# 要素削除
c.remove("A")
print(c)

# 全要素削除
c.clear()
print(c)


# セットを合体
c = {"R", "G", "B"}
a = {"A", "B", "C", "D", "E", "F", "G"}

# c U a (和集合)
set1 = c | a
print(set1)

# c ∩ a (交叉)
set2 = c & a
print(set2)

# 差集合
set3 = c - a
print(set3)

# 対称差
set4 = c ^ a
print(set4)
# Tuple
weight = (82, 28, 50, 58, 63, 82)
print(weight)
print(weight[0])
print(weight[2])
# TypeError: 'tuple' object does not support item assignment
# height[2] = 45
# List
height = [182, 98, 160, 168, 98, 171]
print(height)
print(height[0])
print(height[2])
height[2] = 162
print(height[2])
print(height[-1])
print(len(height))