字符串 數字 列表 元祖 字典 的不同分類and集合的概念
阿新 • • 發佈:2019-01-13
clear remove and 不可 discard 容器 拷貝 pytho pre
可變不可變
1、可變:列表 字典
2、不可變:字符串 數字 元祖
訪問順序:
1、順序訪問:字符串 列表 元祖
2、映射:字典
3、直接訪問:數字
存放元素個數:
容器類型:列表 元祖 字典
原子:數字 字符串
id(變量名)可以查出儲存的位置
s={1,2,3,3,9,8,8} print(id(s))
41383080
集合(set):
1、不同元素組成
2、無序
3、集合中元素必須是不可變類型
例如:
s={1,2,3,3,9,8,8} print(type(s))
輸出
<class ‘set‘>
s = set(‘hellow‘) print(s)
輸出
{‘h‘, ‘w‘, ‘o‘, ‘l‘, ‘e‘}
s = set([‘alex‘,‘alex‘,‘sh‘]) print(s)
輸出
{‘sh‘, ‘alex‘}
有相同的元素自動合並。.add()的用法==〉添加
s = {1, 2, 3, 4, 5, 6} print(s) s.add(‘s‘) s.add(3) print(s) s.add(3) print(s)
輸出
{1, 2, 3, 4, 5, 6} {1, 2, 3, 4, 5, 6, ‘s‘} {1, 2, 3, 4, 5, 6, ‘s‘}
.clear()的用法==〉清空
s = {1, 2, 3, 4, 5, 6} s.clear()print(s)
輸出
set()
.copy()的用法,==>淺拷貝
s = {1, 2, 3, 4, 5, 6} s1=s.copy() print(s1)
輸出
{1, 2, 3, 4, 5, 6}
.pop()的用法,==〉隨機刪除一個元素
s = {1, 2, 3, 4, 5, 6} s.pop() s.pop() print(s)
輸出
{3, 4, 5, 6}
.remove()的用法,==〉指定刪除一個元素,當指定元素不存在會報錯
s = {1, 2, 3, 4, 5, 6} s.remove(6) print(s)
輸出
{1, 2, 3, 4, 5}
.discard()的用法,==〉指定刪除一個元素,當指定元素不存在不會報錯(最好用這個)
s = {1, 2, 3, 4, 5, 6} s.discard(6) print(s)
輸出
{1, 2, 3, 4, 5}
笨方法求交集
python_1 = [‘lcg‘, ‘szw‘, ‘zjw‘] linux_1 = [‘lcg‘, ‘szw‘] python_1andlinux_1 = [] for p_name in python_1: if p_name in linux_1: python_1andlinux_1.append(p_name) print(python_1 and linux_1)
輸出
[‘lcg‘, ‘szw‘]
字符串 數字 列表 元祖 字典 的不同分類and集合的概念