1. 程式人生 > >python集合學習筆記

python集合學習筆記

python的集合與Java的類似大概分為三類

  • list 列表
  • set 去重的集合
  • tuple 不可變的元祖
  • dictionary 字典對應Java中的map

下面記錄下學習的內容 :

以上四類集合都可以理解為容器;

list特點:

  1. 可變集合,可以新增,刪除,覆蓋等操作;
  2. 有序的集合,可以按索引操作
  3. 訪問是可以在集合後面以中括號形式來訪問list[]

tuple特點:

  1. 可以理解為具有部分功能的list
  2. 不可變的集合
  3. 有序
  4. 宣告時以小括號建立,也可以不加括號
  5. 當只有一個元素時要在一個元素後面加逗號來避免發生歧義

set特點:

  1. 無序
  2. 可變
  3. 去重
  4. 宣告方式可以set(list)來宣告順便將list中的元素進行了去重操作
  5. pop方法是隨機刪除元素

dictionary特點:

  1. 字典宣告方法用大括號{key1: value1,key2: value2}
  2. 訪問時可以用中括號【key】也可以name.get(key)略有差別,推薦第二種方法

貼下程式碼:

name2age = {"lixin": 25, "lijing": 25, "liguohui": 32, "liwang": 27}
print(name2age["lijing"])
print(name2age.get("liguohui"))

# this manner to get ele from dictionary if there is no key will exception
# print(name2age["wangermazi"])
print(name2age.get("wangermazi"))

print("lijing" in name2age)
print("liwang" in name2age)

name2age.pop("lijing")

print("lijing" in name2age)

exist = name2age.get("lixin") is not None

print(exist)

a = [1, 2, 3, 4]
b = a
c = [1, 2, 3, 4]
print(a == b)
print(a is b)
print(a == c)
# 'is' is compare Object
print(a is c)
vars = ["lijing", "lixin", "liwang", "liguohui", "lixin"]
name_set = set(vars)

print(name_set.__sizeof__())
print(name_set.__len__())
print(len(name_set))
print(name_set)

# judge ele is contained by set
print("lixin" in name_set)
# python is amazing
print("fanqingna" in name_set)


print(name_set.pop())

print(name_set)