Python3數據類型及轉換


I. 數據類型

Python3將程序中的任何內容統稱為對象(Object),基本的數據類型有數字和字符串等,也可以使用自定義的類(Classes)創建新的類型。

Python3中有六個標准的數據類型:

  • Number(數字)
  • String(字符串)
  • List(列表)
  • Tuple(元組)
  • Set(集合)
  • Dictionary(字典)

Python3的六個標准數據類型中:

  • 不可變數據(3 個):Number(數字)、String(字符串)、Tuple(元組);
  • 可變數據(3 個):List(列表)、Dictionary(字典)、Set(集合)。

1. Number:int, float, bool, complex

a, b, c, d = 1, 2.3, True, 4+5j
print(type(a), type(b), type(c), type(d), type(a+b+c+d), a+b+c+d)

<class 'int'> <class 'float'> <class 'bool'> <class 'complex'> <class 'complex'> (8.3+5j)

2. String:

Python中的字符串用單引號'或雙引號"括起來,同時使用反斜杠\轉義特殊字符。r或R表示原始字符串。

s = r'this is raw string \n \t.'
print(type(s), s)

<class 'str'> this is raw string \n \t.

3. List:

列表是寫在方括號[]之間,用逗號分隔開的元素列表。列表的元素可以是數字、字符串和列表。

4. Tuple: 

元組是寫在小括號()之間,用逗號分隔開的元素列表。

t = (1, 2.3, True, 4+5j, (6, 'abc', ['d', {'id': 9, 'value': 'dict'}]))
print(type(t), t)

<class 'tuple'> (1, 2.3, True, (4+5j), (6, 'abc', ['d', {'id': 9, 'value': 'dict'}]))

5. Set:

集合可以使用{}或set()函數來創建,創建空集合必須用set()。

基本功能是測試成員關系和刪除重復元素。

s1 = {1.2, 4+5j, 'abc', 'abc', 'd'}
s2 = set('abcdde')
print(type(s1), s1, type(s2), s2)
print(s1 - s2, s1 | s2, s1 & s2, s1 ^ s2)

<class 'set'> {1.2, (4+5j), 'd', 'abc'} <class 'set'> {'c', 'a', 'd', 'e', 'b'}
{1.2, (4+5j), 'abc'} {1.2, 'c', 'a', 'd', (4+5j), 'abc', 'e', 'b'} {'d'} {'c', 1.2, 'a', (4+5j), 'abc', 'e', 'b'}

6. Dictionary:

字典通過{}或dict()函數創建,是無序的key:value映射的集合。key必須為不可變類型且唯一。

d1 = {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, 4+5j): [1, 'abc']}
d2 = dict([(1, 'abc'), ('name', {'cn': 'Chinese name', 'en': 'English name'})])
d3 = dict(name={'cn': 'Chinese name', 'en': 'English name'}, one='abc')
print(type(d1), d1, d1[(True, 4+5j)])
print(type(d2), d2, d2[1])
print(type(d3), d3, d3['one'])

<class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, (4+5j)): [1, 'abc']} [1, 'abc']
<class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}} abc
<class 'dict'> {'name': {'cn': 'Chinese name', 'en': 'English name'}, 'one': 'abc'} abc

II.數據類型轉換

 

參考:簡明Python教程(英文原版)、菜鳥教程

         數據類型轉換字符串轉字典


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM