セットする
タプルはlistとstrのハイブリッドであり、setはlistとdictのハイブリッドです。セットにはdictと同様の機能があります。{}中括弧で定義できます。要素はシーケンスされません。つまり、非シーケンスタイプのデータです。また、セット内の要素は、dictのキーと同様に、繰り返し可能ではありません。
1.セットを作成します
1.0リストの作成
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#set type defination
list1=[1,2,3,4,"List"]
set1 = set(list1)
print set1
andy@andy-virtual-machine:~/python_test$ ./example.py
set([1, 2, 3, 4, 'List'])
andy@andy-virtual-machine:~/python_test$
1.1文字列の作成
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#set type defination
set1 = set("Python")
print set1
andy@andy-virtual-machine:~/python_test$ ./example.py
set(['h', 'o', 'n', 'P', 't', 'y'])
andy@andy-virtual-machine:~/python_test$
1.2タプルの作成
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#set type defination
set1 = set((1, 2, 3,"123"))
print set1
andy@andy-virtual-machine:~/python_test$ ./example.py
set(['123', 1, 2, 3])
andy@andy-virtual-machine:~/python_test$ ./example.py
set(['123', 1, 2, 3])
andy@andy-virtual-machine:~/python_test$
1.3辞書の作成
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#set type defination
dict1 = {}
dict1["hobby"] = "reading"
dict1["favorate food"] = "fish"
set1 = set(dict1)
print set1
andy@andy-virtual-machine:~/python_test$ ./example.py
set(['hobby', 'favorate food'])
andy@andy-virtual-machine:~/python_test$
1.4 {}作成
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#set type defination
set1 = {"gender",[1]}
print set1
set2 = {"gender",1}
print set2
andy@andy-virtual-machine:~/python_test$ ./example.py
Traceback (most recent call last):
File "./example.py", line 5, in <module>
set1 = {"gender",[1]}
TypeError: unhashable type: 'list'
andy@andy-virtual-machine:~/python_test$
unhashable:ハッシュできません。変更できます。
hashable:ハッシュ可能、つまり不変です。
2.コレクションタイプ(セット)
#! /usr/bin/python
#coding:utf-8
#set type defination
dict1 = {}
dict1["hobby"] = "reading"
dict1["favorate food"] = "fish"
set1 = set(dict1)
print set1
print type(set1)
andy@andy-virtual-machine:~/python_test$ ./example.py
set(['hobby', 'favorate food'])
<type 'set'>
andy@andy-virtual-machine:~/python_test$