Python lesson_2, 一些简单的基础语法(2)
tips:
列表(List)是一种有序和可更改的集合。允许重复的成员,用方括号。
元组(Tuple)是一种有序且不可更改的集合。允许重复的成员,用圆括号。
集合(Set)是一个无序和无索引的集合。没有重复的成员,用花括号。
词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员,用花括号编写,拥有键和值。
# Author:JOJO
# -*- coding = utf-8 -*-
# @Time :2022/8/11 20:02
# @Author: asus
# @Site :
# @File :.py
# @Software :PyCharm
# 列表(List)是一种有序和可更改的集合。允许重复的成员,用方括号。
# 元组(Tuple)是一种有序且不可更改的集合。允许重复的成员,用圆括号。
# 集合(Set)是一个无序和无索引的集合。没有重复的成员,用花括号。
# 词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。
# 1.列表(List)是一种有序和可更改的集合。允许重复的成员。用方括号。
thislist = ["apple", "banana", "cherry"]
thislist[1] = 'jojo'
print(thislist)
if 'jojo' in thislist:
print('Yes')
thislist.insert(1, 'hailee')
print(thislist)
# 删除的几种方法:remove、pop、del、clear
thislist.remove('hailee')
print(thislist)
thislist.pop(0) # 默认最后一项
print(thislist)
del thislist[1] # 不加索引默认全删
print(thislist)
thislist.clear()
print(thislist)
# 复制
a = list((1, 2)) # 用双括号和list构造函数创造列表
b = list(a)
print(b)
# 2.元组Tuple,元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# 把元组转换成列表就可以改变,用一个list函数即可。
# 如需创建仅包含一个项目的元组,必须在该项目后添加一个逗号。
del thistuple # 不可以删元素,但是可以完全删除。
# print(thistuple)就报错了,因为已经完全删除了。
thistuple = tuple(("apple", "banana", "cherry")) # 和list一样
print(thistuple)
print(thistuple.count('apple'), thistuple.index('banana'))
# 3.集合是无序和无索引的集合。在 Python 中,集合用花括号编写。
thisset = {"apple", "banana", "cherry"}
print(thisset)
# 没有顺序,但是可以用for来遍历
for x in thisset:
print(x)
# 添加一个元素用add,多个用update,union() 和 update() 都将排除任何重复项。
thisset.add("orange")
thisset.update(["jojo", "mango", "grapes"])
print(thisset) # 每次顺序还不一样
# 删除用remove或者discard,用pop也可以,只不过你不知道会删掉哪一个。
thisset.remove("banana")
thisset.discard("mango")
print(thisset)
# 用union合并
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
thisset = set((1, 2)) # 一样的
print(thisset)
# 4.字典是一个无序、可变和有索引的集合。
# 在 Python 中,字典用花括号编写,拥有键和值。(像类?
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
x = thisdict["model"]
y = thisdict.get("model")
print(x, y)
thisdict["year"] = 2019
for x, y in thisdict.items(): # 返回键和值
print(x, y)
thisdict["color"] = "red"
print(thisdict)
# 使用 copy() 方法来复制字典:
mydict = thisdict.copy()
print(mydict)
# 词典也可以包含许多词典,这被称为嵌套词典。
myfamily = {
"child1" : {
"name" : "Phoebe Adele",
"year" : 2002
},
"child2" : {
"name" : "Jennifer Katharine",
"year" : 1996
},
"child3" : {
"name" : "Rory John",
"year" : 1999
}
}
print(myfamily)
# 同样也可以用dict来构造字典。