Python基础(二),,1、列表list#1


1、列表list#1.创建lst = [6, 4, 8, 10 ,2, True, 11.0]#2.获取和设置元素的值print(lst[6]) #获取lst[6] = 11print(lst[6]) #设置lstprint(type(lst)) #list#3.运算符print(lst+[‘a‘,‘b‘,‘c‘]) #[6, 4, 8, 10, 2, True, 11, ‘a‘, ‘b‘, ‘c‘]print(lst*2) #[6, 4, 8, 10, 2, True, 11, 6, 4, 8, 10, 2, True, 11]print(lst[2]) #8print(lst[1:5]) # 4, 8, 10, 2print(lst[1:5:2]) # 4,10print(lst[-1:-5:-2]) #[11, 2]print(lst[:4]) #6, 4, 8, 10#4.方法#1) 查找 index、count、sort、sorted、reverse、reversedlst = [6, 4, 8, 10 ,2, 4]print(lst.index(4)) # 1 ,通过元素查找位置print(lst.index(4, lst.index(4)+1)) #5print(lst.count(4)) # 2lst.sort() #lst本身print(lst) #[2, 4, 4, 6, 8, 10]lst = [6, 4, 8, 10 ,2, 4]lst.sort(reverse=True)print(lst) #[10, 8, 6, 4, 4, 2]lst.reverse() #反转print(lst) #[2, 4, 4, 6, 8, 10]#还有一种排序方法,不是上面的方法sort,而是函数 sortedlst = [3,5,1,7]lst2 = sorted(lst) #默认从小到大print(lst2)lst = [3,5,1,7]lst2 = sorted(lst, reverse=True) #从大到小print(lst2)# 2) 增加 insert、append、extendlst = [1, 3, 5, 7, 9]#在第2个位置,插入4lst.insert(2, 4) print(lst) #[1, 3, 4, 5, 7, 9]#在末尾插入一个元素lst.append(10) # [1, 3, 4, 5, 7, 9, 10]print(lst)#lst.extendlst.extend([11,12,13]) #[1, 3, 4, 5, 7, 9, 10, 11, 12, 13]print(lst)#区别append():不能添加多个元素extend():能添加多个元素,但参数必须是列表insert()lst.append([14,15,16]) #[1, 3, 4, 5, 7, 9, 10, 11, 12, 13,[14,15,16]]print(lst)注:append()、extend()、insert()都不属于BIF,所以使用时都必须指出相应的表# 3)删除 pop、remove、del、clearremove():知道要删除的元素就行del 是一个语句 del+表名pop():弹出最后一个元素,且可根据索引值弹出元素clear()删除全部,但是保留空表lst = [1,2,3, 5, 7, 9]#删除1个:按照索引lst.pop(1) print(lst) #[1, 3, 5, 7, 9]lst.pop() #不写参数,删除最后一个print(lst) #[1, 3, 5, 7]#删除1个:按照内容lst.remove(5)print(lst) #[1, 3, 7]#删除全部lst.clear()print(lst) #[]#删除列表 del lst#print(lst)#拷贝lst = [1,2, 3, 5, 7, 9]lst2 = lst.copy()print(lst2)题目:1、 lst = []for i in range(5): lst.append(i*2)lst#[0, 2, 4, 6, 8]列表表达式[ i*2 for i in range(5)]#[0, 2, 4, 6, 8]2、[[i,i+1] for i in range(5)] #[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]3、[i.upper() for i in ‘hello‘] #[‘H‘, ‘E‘, ‘L‘, ‘L‘, ‘O‘]4、[len(i) for i in ‘I Hate You‘.split()] #[1, 4, 3][len(i) for i in [‘I‘,‘Hate‘,‘You‘]]#[1, 4, 3]5、 lst = []for i in range(5): if i*2 <= 4: lst.append(i*2)lst#[0, 2, 4][i*2 for i in range(5) if i*2<=4]#[0, 2, 4]6、[(i,i+1,i+2,i+3) for i in range(5)]#[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]7、lst = []for i in [1,2,3]: for j in [3,1,4]: if i != j: lst.append((i,j))lst#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)][(i,j) for i in [1,2,3] for j in [3,1,4] if i != j]#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]8、vec = [[1,2,3], [4,5,6], [7,8,9]][num for elem in vec for num in elem]#[1, 2, 3, 4, 5, 6, 7, 8, 9]lst = []for elem in vec: for num in elem: lst.append(num)lst#[1, 2, 3, 4, 5, 6, 7, 8, 9]2、元组tuple# 1.创建t1 = (1, 1.0, True)t2 = 1, 1.0, True #小括号可以省略t3 = (1,) #如果只有1个数,后面需要加入逗号t4 = 1,t5 = (1) #这个不是元组,它是整数,也就1print(type(t1)) #tupleprint(type(t2))print(type(t3))print(type(t4))print(type(t5)) #intt = 12345, 54321, ‘hello!‘print(t[0]) #12345print(t) # (12345, 54321, ‘hello!‘)u = t, (1, 2, 3, 4, 5)print(u) #((12345, 54321, ‘hello!‘), (1, 2, 3, 4, 5))#元组的赋值:比较灵活a,b,c=1,2,3print(a, b, c)a,b,c=‘123‘print(a, b, c)(a,b,c)=(1,2,3)print(a, b, c)a=1,2,3print(a) #(1,2,3)#元组和列表的相互转换,用list函数和tuple函数list((1, 2, 3)) # 元组变列表tuple([1, 2, 3]) #列表变元组#列表和字符串的相互转换list(‘abc‘) #字符串变列表 [‘a‘, ‘b‘, ‘c‘]‘‘.join([‘a‘, ‘b‘, ‘c‘])#列表变字符串 ‘abc‘3、集合(无序、不重复)set1 = {4, 6, 11, 3, 1, 3}for i in set1: print(i)print(type(set1)) #set#list转成set,用set函数 :可以把list的重复元素去掉set2 = set([1, 3, 3, 3, 5, 7]) #list转成set类型print(set2)#str转set,也是用上面set方法#创建空集合set1 = {} #这么写是错的,原因是字典占用了。set1 = set() #这些是对的注:1、集合是无序的,所以不能像序列一样访问,可以通过迭代的方法读出来;2、in or not in 判断元素是否存在 3、add()、remove()增加和删除已知元素4、frozenset()将集合里的元素冰冻4、字典#1. 创建(1)fromkeys()创建并返回一个新的字典(2)keys()、values()、items()(3)get(键)访问字典(4)copy()复制字典,值相同,位置不同(5)pop()弹出字典的值,popitem()弹出字典的项(6)update(键+值)更新字典#方法1:最常用dic1 = {‘cn‘:‘china‘, ‘us‘:‘America‘, ‘age‘:18}print(dic1)print(type(dic1)) #dict#方法2:key值不能加引号dic2 = dict(cn=‘china‘, us=‘America‘)print(dic2)#方法3:实际是把列表中的元组元素,转成字典dic3 = dict([(‘cn‘,‘china‘),(‘us‘,‘America‘)])print(dic3)#创建空字典dic4 = {}print(type(dic4))#获取和设置元素dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}print(dic[‘cn‘]) #获取值:通过key获取valuedic[‘cn‘] = ‘CHINA‘ #设置值print(dic[‘cn‘])#如果key不存在,会出错#print(dic[‘xxx‘]) #如果key不存在,不想报错,可以用get方法,同时get还可以可以设置默认值print(dic.get(‘xxx‘)) #返回None print(dic.get(‘xxx‘, ‘yyyy‘)) #xxx不存在,返回yyyy#2)运算符dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}print(‘cn‘ in dic) #Trueprint(‘jp‘ not in dic) #True#3)方法#增dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}dic[‘fr‘] = ‘french‘ #增加print(dic)dic.update({‘a‘:‘1‘,‘b‘:‘2‘})print(dic)#删dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}dic.pop(‘us‘) #通过key删除一行print(dic)dic.clear() #清空print(dic) #{}#改dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}dic[‘cn‘] = ‘CHINA‘print(dic)#查dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}#1)通过key查vlaueprint(dic[‘cn‘]) #方便,但是如果没有查到,会报错print(dic.get(‘cn‘)) #没有查到,返回None,还可以设置默认值#2)查询所有的keyprint(dic.keys())for key in dic.keys(): print(key,dic[key])#3)查询所有的valueprint(dic.values())#4)查询所有的itemprint(dic.items())for item in dic.items(): print(item[0],item[1]) for (k,v) in dic.items(): print(k,v)#拷贝dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}dic2 = dic.copy()print(dic2)dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}for x in dic: #如果直接写字典的名称,取得值是key print(x)list(zip([1,3,5],[‘a‘, ‘b‘, ‘c‘]))5、函数def foo1(): return 1;print(foo1())def foo2(): print(1)foo2()#分别求1到100, 1到200的和def foo(n):sum = 0for i in range(n+1):sum += ireturn sumprint(foo(100))result = foo(200)print(result)#修改水仙花数def foo(): for number in range(100, 1000): a = number % 10 #个位数 b = number //10 % 10 #十位数,或number%100//10 c = number // 100 #百位数 if is_narcissistic(number, a, b, c): print(number) def is_narcissistic (digit, x, y, z): if digit == x**3 + y**3 + z**3: return True else: return False foo()#改写求闰年def is_leap_year(y): if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0): return True else: return Falsedef foo(): year = 3000 if is_leap_year(year): print(‘%d是闰年‘%year) else: print(‘{}不是闰年‘.format(year))foo()def sum(a, b, c):return a + b + csum(1, 2, 3) #6def ask(a,b=1,c=‘ok‘):passask(‘hello‘)ask(‘hello‘,2)ask(‘hello‘,2,‘yes‘)ask(b=2,a=‘hello‘)ask(‘hello‘,c=‘yes‘)#ask(a=1,2,‘3‘) #出错#可变长参数传递def foo(a,*b):print(type(a)) #strprint(type(b)) #tupllefoo(‘hello‘,1,2,3,4)def sum(*a): total = 0 for i in a: total += i print(total)sum(1,2) #3sum(1,2,3) #6sum(1,2,3,4) #10#参数是字典def foo(a, *b, **c): print(a) #hello print(b) #1,2,3,4 print(c) # {cn=‘china‘,us=‘america‘}foo(‘hello‘,1,2,3,4,cn=‘china‘,us=‘america‘)#高阶函数:参数是函数的函数def add(a,b):return a + bdef minus(a,b):return a - bdef foo(x, y, f): return f(x,y)print(foo(1,2,add))print(foo(1,2,minus))x = 0 # Global变量def m1():#global xx = 1 #Enclosing变量def m2():nonlocal xx = 2 #Local变量print(x) #2m2()print(x) #2m1() print(x) #0#匿名函数func = lambda x,y: x + yfunc(1,2)(lambda x,y:x + y)(1,2)def foo(): for i in range(1,8): print(‘第‘,i,‘步‘) yield i*2gen = foo() print(type(gen)) #generatorgen.__next__() # 2gen.__next__() #4#定义装饰器def xxx(f):def yyy(a,b):print(‘----‘)return f(a,b)return yyy@xxxdef add(x,y):return x+yprint(add(4,5)) # 9print(add(1,2)) # 3def outer(x):def inner(y):return x + yreturn innerf = outer(5)f(3) # 8

Python基础(二)

评论关闭