列表(List)

列表是一个有序且可更改的集合。在 Python 中,列表用方括号编写。允许重复的成员。

thislist = ["apple", "banana", "cherry"]    # 索引与元组类似

thislist[1] = "mango"           # 更改项目值
thislist.append("orange")       # 将项目添加到列表的末尾
thislist.insert(1, "orange")    # orange成第二个项目
thislist.remove("banana")       # 删除项目
thislist.pop()                  # 删除指定项目
thislist.clear()                # 清空列表

# 复制列表
mylist = thislist.copy()        
mylist = list(thislist)

# 合并列表
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
# 或者 追加列表
for x in list2:
  list1.append(x)
list1.extend(list2)         # 将一个列表中的元素添加到另一列表

thislist = list(("apple", "banana", "cherry")) # 创造列表 请注意双括号

元组(Tuple)

元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。允许重复的成员。

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon")

# 负索引表示从末尾开始,-1 表示最后一个项目,-2 表示倒数第二个项目,依此类推。
print(thistuple[-1])
print(thistuple[2:5])       # 返回第3,4,5个项目,从0开始,包括2,不包括5
print(thistuple[-4:-1])     # 包括-4 不包括-1

创建元组后,无法更改其值。但是可以将元组转换为列表,更改列表,然后将列表转换回元组。

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

字典(Dictionary)

字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。没有重复的成员。

thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
# 获得键的值
x = thisdict["model"]
x = thisdict.get("model")

thisdict["year"] = 2019     # 更改值

# 判断 字典中是否存在 "model"
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

for x in thisdict:
  print(x)                  # 获得所有键名
  print(thisdict[x])        # 获得所有键值

# 获得所有键值
for x in thisdict.values():
  print(x)

# items() 遍历键和值
for x, y in thisdict.items():
  print(x, y)

thisdict["color"] = "red"   # 添加项目
thisdict.pop("model")       # 删除项目
thisdict.clear()            # 清空字典
dict.get(key, default=None)

集合(Set)

集合是无序和无索引的集合。在 Python 中,集合用花括号编写。没有重复的成员。无法通过引用索引来访问 set 中的项目
集合一旦创建,无法更改项目,但是添加新项目。

thisset = {"apple", "banana", "cherry"}
thisset = set(("apple", "banana", "cherry"))

thisset.add("orange")           # 将一个项添加到集合
thisset.update(["orange", "mango", "grapes"])   # 向集合中添加多个项目

# 删除项目,有多种方法
thisset.remove("banana")        # 如果要删除的项目不存在,报错
thisset.discard("banana")       # ~,不会引发错误
x = thisset.pop()               # 删除最后一项,但因为set无序,所以是随机删的,返回被删的值

set3 = set1.union(set2)         # 合并集合
set1.update(set2)               # 这两种都将排除任何重复项

集合的交并差运算

set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}
# 交集
print(set1 & set2)                # {2, 4, 6}
print(set1.intersection(set2))    # {2, 4, 6}

# 并集
print(set1 | set2)         # {1, 2, 3, 4, 5, 6, 7, 8, 10}
print(set1.union(set2))    # {1, 2, 3, 4, 5, 6, 7, 8, 10}

# 差集
print(set1 - set2)              # {1, 3, 5, 7}
print(set1.difference(set2))    # {1, 3, 5, 7}

# 对称差,不算交集的剩下两个加起来
print(set1 ^ set2)                        # {1, 3, 5, 7, 8, 10}
print(set1.symmetric_difference(set2))    # {1, 3, 5, 7, 8, 10}
print((set1 | set2) - (set1 & set2))      # {1, 3, 5, 7, 8, 10}

类/对象

代码笔记

  • print 中 end 的用法,相当于替换\n换行
>>>print('ABC',end ='123')
>>>print('DEF')
ABC123DEF