# 1 list列表=================================================
# list是一种有序的集合,可以随时访问、添加和删除其中的元素
#
仅从操作方式上看,列表像是数组和链表的综合体。
# 除按索引访问外,还支持插入、添加、删除等操作,完全可当作队列和栈使用。
# 如不考虑性能问题,列表似乎是一种易使用且功能完善的理想数据结构。
# 创建list
classmate = ["Mike","Bob","Tracy"]
print(classmate)
#(#……代表print输出)
#……["Mike", "Bob", "Tracy"]
# 由于python是动态语言,所以list中包含的元素并不要求都必须是同一种数据类型
L = ["Mike",100,True]
print(L)
#……["Mike", 100, True]
# 按照索引访问list
print(classmate[0])
#……Mike
# list还可以倒序访问
print(classmate[-1])
#……Tracy
# 添加新元素
classmate.append("wwu")
print(classmate)
#……["Mike", "Bob", "Tracy", "wwu"]
# 插入新元素
classmate.insert(0,"zwu")
print(classmate)
#……["zwu", "Mike", "Bob", "Tracy", "wwu"]
# 从list未尾删除元素
classmate.pop()
print(classmate)
#……["zwu", "Mike", "Bob", "Tracy"]
# 从list指定位置删除元素
classmate.pop(2)
print(classmate)
#……["zwu", "Mike", "Tracy"]
#list中替换元素
classmate[1] = "Lisa"
print(classmate)
#……["zwu", "Lisa", "Tracy"]
#把一个list拼接成一个字符串
print(" ".join(classmate))
#……zwu Lisa Tracy
#对list进行slice切片操作
# 也就是取list的部分数据,[start,end]
li = [0,1,2,3,4,5,6]
print(li[0:4])
#……[0, 1, 2, 3]
# li[0:4]可以简写成li[:4]
print(li[4:6])
#……[4, 5]
print(li[:])
#……[0, 1, 2, 3, 4, 5, 6]
# 切片操作还可以指定第三个参数
print(li[::2])
#……[0, 2, 4, 6]
# 第三个参数表示每N个取一个,上面的[::2]表示每两个取一个,也就是隔一个取一个
# 倒序切片
print(li[-2:])
print(li[:-2])
#……[5, 6]
#……[0, 1, 2, 3, 4]
# 字符串切片
# 字符串 "xx" 和Unicode字符串 u"xxx"也可以看成是一种list,每个元素就是一个字符
str = "abcdefg"
print(str[:5])
#……abcde
# 2 tuple元组======================================================
# 元组是一个“只读”的list,创建后不能再修改
# 没有append、insert、pop等list方法;
# 按索引访问的方法与list是一样的
Tclassmate = ("Mike","Bob","Tracy")
print(Tclassmate)
#……("Mike", "Bob", "Tracy")
print(Tclassmate[-1])
#……Tracy
# tuple内可以包含可变的list
t = (1,2,3,[4,5,6])
print(t)
#……(1, 2, 3, [4, 5, 6])
# tuple内的list对象可以通过t[3]拿到
tl = t[3]
print(tl)
#……[4, 5, 6]
tl[0]=40
print(t)
#……(1, 2, 3, [40, 5, 6])
# 3 循环与语句块====================================================
# for语句
for name in classmate:
print(name)
#output:
"""
zwu
Lisa
Tracy
"""
# 上面循环语句后的冒号:表示语句块的开始,相同的缩进表示一个语句块
# 缩进统一用4个空格表示
# 如果你在交互环境下敲代码,退出缩进需要多敲一行回车
# 4 dict字典====================================================
# list和tuple可用用来表示顺序集合,如班里的名字和考试成绩的列表:
Ln = ["Adam","Lisa","Seldon"]
Lc = [95,86,61]
# 如果要根据名字找到对应的成绩,用两个list表示就不是很方便
# python的dict就可以把名字和成绩关联起来,组成键值项
# dict的定义:{key:value,……}
d = {
"Adam":95,
"Lisa":86,
"Seldon":61
}
print(d)
#……{"Adam": 95, "Lisa": 86, "Seldon": 61}
# 计算集合的大小
print(len(d))
#……3
# 访问dict,不同于list和tuple使用索引,dict使用key访问
print(d["Seldon"])
#……61
# 通过key访问dict的value,只要key存在,dict就返回对应的value;
# 如果key不存在,会直接报错:keyError
# 要避免keyError发生,有两个方法:
# I 用in操作符判断key是否存在
if "Lisa" in d:
print(d["Lisa"])
# II 使用dict提供的一个get方法,在key不存在时,返回None
print(d.get("Seldon"))
#……61
print(d.get("wwu6"))
#……None
# dict的特点
# I 查找速度快,但占用内存大;
# II 由于dict是按key查找的,所在在一个dict中,key不能重复;
# III 元素键值对key:value没有顺序;
# IV key不可变,不能用list作key,字符串、整数、浮点数都行,当然list可以用作value;
# 更新dict
d["wwu"] = 66
print(d)
#……{"Adam": 95, "Lisa": 86, "Seldon": 61, "wwu": 66}
# 如果key存在,则赋值会用新的value代替原来的value
d["Seldon"] = 99
print(d)
#……{"Adam": 95, "Lisa": 86, "Seldon": 99, "wwu": 66}
# 遍历dict
for key in d:
print(key)
#output:
"""
Adam
Lisa
Seldon
wwu
"""
# 5 set集合=================================================
# dict的作用是建立一组key和value的对应关系,dict的key是不能重复的;
# 有时候,我们只需要考虑key是否存在,这时set就派上用场了
# set持有一系列元素,这一点与list很像;
# 但是set的元素没有重复,而且是无序的,这一点与dict的key很像
# 创建set,一般用list来创建set
s = set(classmate)
print(s)
#……{"zwu", "Lisa", "Tracy"}
# 求set大小
print(len(s))
#……3
# 遍历set
for names in s:
print(names)
#output:
"""
zwu
Tracy
Lisa
"""
# 使用操作符in访问set中的元素
print("Lisa" in s)
#……True
# set的特点
# I set的内部结构与dict很像,唯一的区别是不存储value,因此,判断一个元素是否在set中速度很快
# II set存储的元素和dict的key类似,必须是不变对象;
# III set存储的元素没有顺序;
# set应用
weekdaysS = ["Mon","Tue","Wed","Thu","Fri","Sat","sun"]
weekdays = (weekdaysS)
x = "Thu"
if x in weekdays:
bo = True
else:
bo = False
print(bo)
#……True
# 更新set之添加元素
s.add("wwu2")
print(s)
#……{"zwu", "Lisa", "Tracy", "wwu2"}
# 如果添加的元素已经存在于set中,add()不会报错,但也不会把元素添加进去
# 更新set之删除元素
s.remove("wwu2")
print(s)
#……{"Tracy", "zwu", "Lisa"}
# 如果想要删除的元素在set中不存在,remove()会报错
#6 函数==========================
def power(x,n):
s = 1
while n>0:
n = n - 1
s = s * x
return s
print(power(2,10))
#……1024
# 函数也可以定义默认参数
def power(x,n = 2):
s = 1
while n>0:
n = n - 1
s = s * x
return s
print(power(100))
#……10000
# 可以返回多值
def op(a,b):
x = a + b
y = a - b
return x,y
print(op(9,7))
#……(16, 2)
i,j = op(9,7)
print(i,j)
#……16 2
# 递归函数
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
print(fact(10))
#……3628800
# 定义可变参数
# 也就是函数可以接收任意多个参数
def fn(*args):
print(args)
print(fn(1,2,3))
#……(1, 2, 3)
#在可变参数函数中,变量args相当于一个tuple
def average(*args):
sum = 0;
i = 0;
for n in args:
sum = sum + n
i = i + 1
return sum/i
print(average(61,86,99))
#……82.0
# 7 有序集合的索引iteration迭代========================================
# 在python中,迭代是通过for……in来完成的
# in后的集合可以用在list、tuple、dict、set上,也可以用在其他任何可以迭代的对象上
# 迭代操作就是依次取出一个集合中的每一个元素,集合可以是无序或有序
# 索引迭代
for index, name in enumerate(s):
print(index, "-", name)
#output:
"""
0 - Tracy
1 - zwu
2 - Lisa
"""
# enumerate(s)把["Tracy", "zwu", "Lisa"]变成了类似:
# [(0,"Tracy"),(1,"zwu"),(2,"Lisa")]
# 所以上面的迭代相当于以下结构
for t in enumerate(s):
index = t[0]
name = t[1]
print(index, "-", name)
#output:
"""
0 - Tracy
1 - zwu
2 - Lisa
"""
# 迭代dict的value
for v in d.values():
print(v)
#output:
"""
95
86
99
66
"""
# 迭代键值对
for v in d.items():
print(v)
#output:
"""
("Adam", 95)
("Lisa", 86)
("Seldon", 99)
("wwu", 66)
"""
# 在迭代的键值对取value
for v in d.items():
print(v[1])
#output:
"""
95
86
99
66
"""
#用迭代生成列表
lin = []
for x in range(1,11):
lin.append(x)
print(lin)
#……[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 把迭代放在表达式中
lin2 = [x for x in range(1,11)]
print(lin2)
#……[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#for循环迭代dic
print(d)
#……{"Adam": 95, "Lisa": 86, "Seldon": 99, "wwu": 66}
tds=["
%s%s"%(name,score) for name, score in d.items()]print("
print("
NameScore")print("".join(tds))
print("
")#……
"""
Name | Score |
---|---|
Adam | 95 |
Lisa | 86 |
Seldon | 99 |
wwu | 66 |
"""
# for循环和if判断生成list
list2 = [x*x for x in range(1,11) if x % 2 == 0]
print(list2)
#……[4, 16, 36, 64, 100]
# 多层表达式
list3 = [m+n for m in "ABC" for n in "123"]
print(list3)
#……["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
#以上结构相当于:
list4 = []
for m in "ABC":
for n in "123":
list4.append(m+n)
print(list4)
#……["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
# 把函数作为参数
def add(x,y,func):
return func(x) + func(y)
print(add(5,-8,abs))
#……13
# map()函数
list5 = [x for x in range(1,11)]
def funct(x):
return x*x
list6 = list(map(funct,list5))
print(list6)
#……[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# map函数依次接收列表的每个元素作为参数完成函数的计算,形成一个新的列表,
# 相当于一个函数列表,每个函数的参数是作为参数的列表的每个元素
# filter()函数
def isodd(x):
return x%2 == 1
list8 = list(filter(isodd,list5))
print(list8)
#……[1, 3, 5, 7, 9]
def isnotempty(s):
return s and len(s.strip()) > 0
str = list(filter(isnotempty," this is a test "))
print("".join(str))
# ……thisisatest
a = " 123 "
print(a.strip())
#……123
# list排序函数
# python内置函数可对list进行排序
list0 = [36,5,12,9,21]
list2 = sorted(list0)
print(list2)
#……[5, 9, 12, 21, 36]
# list倒序排序
list3 = sorted(list0,reverse=True)
print(list3)
#……[36, 21, 12, 9, 5]
# sorted也支持对字符串元素进行排序,默认按ASCII大小来比较
list4 = ["John","Henrry","zwu","Zyi","john"]
list5 = sorted(list4)
print(list5)
#……["Henrry", "John", "Zyi", "john", "zwu"]