>>> 10
10
>>> 0b1010
10
>>> 0o12
10
>>> 0xA
10
上面都是整數型態,下面這幾種回傳的都是字串型態
>>> oct(10)
'0o12'
>>> hex(10)
'0xa'
>>> bin(10)
'0b1010'
>>> type(10)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type(3.14e-10)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>>
>>> import a
a
>>> type(a)
<class 'module'>
>>> 10 + 1j
(10+1j)
>>> type(10 + 1j)
<class 'complex'>
>>> type([])
<class 'list'>
建立清單
>>> numbers = [1,2,3]
>>> numbers
[1, 2, 3]
>>> type(numbers)
<class 'list'>
>>> numbers.append(5)
>>> numbers[1]
2
反向取用
>>> numbers[-1]
5
>>> numbers
[1, 2, 3, 5]
>>> numbers[3] = 0
>>> numbers.remove(0)
>>> numbers
[1, 2, 3]
>>> del numbers[0]
>>> numbers
[2, 3]
>>> 2 in numbers
True
>>> 3 in numbers
True
>>> 10 in numbers
False
>>> numbers.clear()
>>> numbers
[]
>>> numbers.extend([10, 11, 12])
>>> numbers
[10, 11, 12]
建立集合只能夠過set(),想要透過{}產生集合式不行的,你只會得到一個字典dict,並且並非所有的元素都能夠放入集合。
>>> users=set()
>>> users.add('cat')
>>> users.add('jet')
>>> users
{'cat', 'jet'}
>>> users.remove('cat')
>>> 'cat' in users
False
>>> 'jet' in users
True
集合可以從其他可迭代的物件中建立set,像是字串, list, 和tuple等
>>> set('哈樓! 世界!')
{'樓', '哈', '世', ' ', '!', '界'}
>>> set([1,3,4])
{1, 3, 4}
>>> set((5,3,5,4))
{3, 4, 5}
測試要把一些特殊的元素放進去set是無法的,因為集合的特性就是元素不會重複,所以需要有可辨別元素差異。
>>> {[1, 2, 3]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> x={}
>>> type(x)
<class 'dict'>
>>> {{1, 2, 3}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> set([{1,3}])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> type({})
<class 'dict'>
>>> pwd = {'justin' : 123456, 'cat' : 933933}
>>> pwd['justin']
123456
>>> pwd['cat']
933933
>>> pwd
{'cat': 933933, 'justin': 123456}
>>> pwd['iron'] = 9777
>>> pwd
{'cat': 933933, 'iron': 9777, 'justin': 123456}
>>> del pwd['cat']
>>> pwd
{'iron': 9777, 'justin': 123456}
>>> pwd['mary']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'mary'
>>> pwd.get('mary')
>>> pwd.get('mary') == None
True
>>> pwd.get('mary', 9119)
9119
>>> list(pwd.items())
[('iron', 9777), ('justin', 123456)]
>>> list(pwd.keys())
['iron', 'justin']
>>> list(pwd.values())
[9777, 123456]
>>> pwd.values()
dict_values([9777, 123456])
>>> x = pwd.values()
>>> type(x)
<class 'dict_values'>
在python3之中會傳回dict_values,在python2裏面則是回傳list
建立字典的方式除了{}方法外,還可以用dict()來建立
>>> pwd=dict(justin=123456, momor=670723, hamimi=970221)
>>> pwd
{'momor': 670723, 'hamimi': 970221, 'justin': 123456}
>>> pwd=dict([('jusin',123456), ('momor', 670723), ('hamimi',970221)])
>>> pwd
{'momor': 670723, 'jusin': 123456, 'hamimi': 970221}
>>> pwd.fromkeys(['jusin', 'momor'], 'NEED_TO_CHANGE')
{'momor': 'NEED_TO_CHANGE', 'jusin': 'NEED_TO_CHANGE'}
>>> type(())
<class 'tuple'>
簡化寫法是在某個執後面加上,就行了,另外最後一個,可以省略
>>> 10,
(10,)
>>> type(_)
<class 'tuple'>
>>> 10,20,30
(10, 20, 30)
>>> type(_)
<class 'tuple'>
>>> 10,(20,30)
(10, (20, 30))
>>> 10,[20,30]
(10, [20, 30])
>>> act=1, 'justin', True
>>> act
(1, 'justin', True)
可以透過[]存取元素
>>> act[2]
True
>>> act[0]
1
>>> act[-2]
'justin'
另外可以拆解tuple中的每個元素到個別的變數
>>> id, name, verified = act
>>> id
1
>>> name
'justin'
>>> verified
True
因為有以上特性,所以常常被用來交換內容
>>> x=10
>>> y=20
>>> x,y=y,x
>>> x
20
>>> y
10
Python3還有進階的拆解功能Extened Iterable Unpacking
>>> a, *b = (1,2,3,4,5)
>>> a
1
>>> b
[2, 3, 4, 5]
>>>
>>> type(None)
<class 'NoneType'>
>>> type(False)
<class 'bool'>
>>> type(True)
<class 'bool'>
>>> type('')
<class 'str'>
>>> type("")
<class 'str'>
不論單雙引號都是支援跳脫字元的
>>> 'c:\test\abc'
'c:\test\x07bc'
>>> "c:\test\abc"
'c:\test\x07bc'
>>> '\101'
'A'
這是8進位指定字元,只支援3位數號碼
>>> "\x41"
'A'
這是16位元16進位指定字元,只支援4位數號碼
>>> "\u54C8"
'哈'
這是16位元16進位指定字元,只支援8位數號碼
>>> "\U000054C8"
'哈'
這是32位元16進位指定字元
>>> "a\"b"
'a"b'
字串轉換
>>> float('1.414')
1.414
>>> int('1414')
1414
>>> int('141.4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '141.4'
>>> int('10',2)
2
>>> int('10',8)
8
>>> int('10',16)
16
>>> bool('false')
True
>>> bool('False')
True
>>> bool('true')
True
>>> bool('True')
True
>>> bool(0)
False
>>> bool(1)
True
>>> str(3.14)
'3.14'
>>> str(10)
'10'
>>> str(0b10)
'2'
>>> ord('哈')
21704
>>> chr(21704)
'哈'
類似C/C++的格式化字串。不過多一個%r是以repr()函數取得輸出字串
>>> "%x" % 10
'a'
>>> "%X" % 10
'A'
>>> "%o" % 10
'12'
>>> "%x%x" % (10, 11)
'ab'
>>> '{} 除以 {} 是 {}'.format(10, 3, 10/3)
'10 除以 3 是 3.3333333333333335'
>>> '{2} 除以 {1} 是 {0}'.format(10/3, 3, 10)
'10 除以 3 是 3.3333333333333335'
>>> '{n1} 除以 {n2} 是 {result}'.format(result=10/3, n1=10, n2=3)
'10 除以 3 是 3.3333333333333335'
加上類似C/C++的格式化字串,
不過<,^,>是置左, 中, 右;填充字元則是寫在最前面
>>> '{0:d} 除以 {1:d} 是 {2:f}'.format(10, 3, 10/3)
'10 除以 3 是 3.3333333333333335'
>>> '{0:5d} 除以 {1:5d} 是 {2:10.2f}'.format(10, 3, 10/3)
' 10 除以 3 是 3.33'
>>> '{0:<5d} 除以 {1:>5d} 是 {2:.2f}'.format(10, 3, 10/3)
'10 除以 3 是 3.33'
>>> '{0:*^5d} 除以 {1:!^5d} 是 {2:.2f}'.format(10, 3, 10/3)
'*10** 除以 !!3!! 是 3.33'
>>> '{0:*<5d} 除以 {1:!>5d} 是 {2:.2f}'.format(10, 3, 10/3)
'10*** 除以 !!!!3 是 3.33'
只格式化單一數值字串
>>> format(3.14159, '.2f')
'3.14'
格式化字串使用特殊型態
>>> names = ['Justin', 'Monica', 'Irene']
>>> 'All names: {n[0]}, {n[1]}, {n[2]}'.format(n= names)
'All names: Justin, Monica, Irene'
>>> passwords = {'Justin' : 123456, 'Monica': 654321, 'Irene': 11111}
>>> 'The password of Justin is {passwds[Justin]}'.format(passwds = passwords)
'The password of Justin is 123456'
>>> import sys
>>> 'My platform is {pc.platform}'.format(pc = sys)
'My platform is linux'
>>> text='哈'
>>> len(text)
1
>>> text.encode('UTF-8')
b'\xe5\x93\x88'
>>> text.encode('Big5')
b'\xab\xa2'
b是byte array
>>> big5_impl = text.encode('Big5')
>>> type(big5_impl)
<class 'bytes'>
>>> big5_impl.decode('Big5')
'哈'
python 3.5.2
>>> x='哈樓'
>>> type(x)
<class 'str'>
>>> len(x)
2
>>> ux=u'哈樓'
>>> type(ux)
<class 'str'>
>>> len(ux)
2
python 2.7.6
如果字串沒有用u來起頭,則len會獲得整個字串的位元組數目。反之,會用。
>>> x='哈樓'
>>> type(x)
<type 'str'>
>>> len(x)
6
>>> ux=u'哈樓'
>>> type(ux)
<type 'unicode'>
>>> len(ux)
2
>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list1 == list2
True
>>> list1 is list2
False
Python的is運算是比較兩個的參考,如果不是參考到同一個就回傳False
所以將list2指定給list1,會發現list1 is list2為True
>>> list1 = list2
>>> list1 == list2
True
>>> list1 is list2
True
而這時候移除list2中的一個元素list1也會改變,因為是參考到同一個物件
>>> list2.remove(1)
>>> list1 is list2
True
>>> list2
[2, 3]
>>> list1
[2, 3]
用id測試可知變化
>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> id(list1)
140427951415624
>>> id(list2)
140427951415880
>>> list1 = list2
>>> id(list1)
140427951415880
>>> id(list2)
140427951415880
另外可查看有幾個名稱參考到同一個物件
>>> import sys
>>> sys.getrefcount(list1)
2
>>> sys.getrefcount(list2)
2
浮點運算
>>> import sys
>>> import decimal
>>>
>>> n1 = float('1.0')
>>> n2 = float('0.8')
>>> d1 = decimal.Decimal('1.0')
>>> d2 = decimal.Decimal('0.8')
>>>
>>> print('non-decimal')
non-decimal
>>> print('{0} + {1} = {2}'.format(n1, n2, n1+n2))
1.0 + 0.8 = 1.8
>>> print('{0} - {1} = {2}'.format(n1, n2, n1-n2))
1.0 - 0.8 = 0.19999999999999996
>>> print('{0} * {1} = {2}'.format(n1, n2, n1*n2))
1.0 * 0.8 = 0.8
>>> print('{0} / {1} = {2}'.format(n1, n2, n1/n2))
1.0 / 0.8 = 1.25
>>>
>>> print('decimal')
decimal
>>> print('{0} + {1} = {2}'.format(d1, d2, d1+d2))
1.0 + 0.8 = 1.8
>>> print('{0} - {1} = {2}'.format(d1, d2, d1-d2))
1.0 - 0.8 = 0.2
>>> print('{0} * {1} = {2}'.format(d1, d2, d1*d2))
1.0 * 0.8 = 0.80
>>> print('{0} / {1} = {2}'.format(d1, d2, d1/d2))
1.0 / 0.8 = 1.25
其他數學運算
>>> 10/3
3.3333333333333335
>>> 10//3
3
>>> 10/3.0
3.3333333333333335
>>> 10//3.0
3.0
>>> 2**3
8
>>> 9**0.5
3.0
>>> 2.2 % 2
0.20000000000000018
>>> 2.2 %% 2
File "<stdin>", line 1
2.2 %% 2
^
SyntaxError: invalid syntax
>>> 2.2 % 2
0.20000000000000018
>>> 2 % 2
0
>>> 3 % 2
1
>>> -3 % 2
1
>>> -7 % 2
1
數學運算運用在string, list, tuple
>>> '10' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> '10' + str(1)
'101'
>>> int('10') + 1
11
>>> text1*10
'hellohellohellohellohellohellohellohellohellohello'
>>> text1**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
>>> text1*10/5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> num1 = ['one', 'two']
>>> num2 = ['three', 'four']
>>> num1+num2
['one', 'two', 'three', 'four']
>>> num1*4
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']
關於set的操作稍微有些不同
>>> a=set(['one', 'two'])
>>> b=set(['one', 'thr'])
>>> a
{'two', 'one'}
>>> b
{'thr', 'one'}
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'set' and 'set'
>>> a-b
{'two'}
對set作xor, or, and運算
>>> a^b
{'thr', 'two'}
>>> a | b
{'thr', 'two', 'one'}
>>> a & b
{'one'}