5.每日知识归类之第五天综合(十二 流程控制之if...else 十三 流程控制之while循环 十四 流程控制之for循环 )

------------------------------------------------------------day 5-----------------------------------------------------

 

一、补充for循环

  1. enumerate()
goods=['mac','apple','iphone','tesla']
for i in range(len(goods)):
    print(i,goods[i])
for i in enumerate(goods):     #enumerate用于for循环,更简单
    print(i)                       #输出元组
print(enumerate(goods))        #转成enumerate object
for x,y in enumerate(goods):
    print(x,y)

 

   0 mac

   1 apple

   2 iphone

   3 tesla

   (0, 'mac')

   (1, 'apple')

   (2, 'iphone')

   (3, 'tesla')

   <enumerate object at 0x1044fdaf8>

   0 mac

   1 apple

   2 iphone

   3 tesla

 

  1. list与for循环
print(list('hello'))  #list()将字符串转化成list类型,相当于以下形式的简写(for循环)。 list本质是for循环,依次取出元素,生成一个列表; 所以可用for取值的就可以放入list中

l=[]
for item in 'hello':
    l.append(item)
print(l)

print(list(enumerate('hello'))) #将enumerate()生成的元组转化为list

for x,y in enumerate('hello'):
    print(x,y)

 

['h', 'e', 'l', 'l', 'o']

['h', 'e', 'l', 'l', 'o']

[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

0 h

1 e

2 l

3 l

4 o

 

  1. for循环可以循环字典,默认拿字典的key值
   msg_dict={'name1':'alex','name2':'egon','name3':'wxx'}
   for k in msg_dict:
       print(k, msg_dict[k])

 

  name1 alex

  name2 egon

  name3 wxx

 

  1. for练习题讲解(九九成法表,打印金字塔)

#外层循环循环一次,内层循环要完整循环完

     print('a')  #因为print默认end ='\n完成打印后换行
     print('a',end ='\n') #此种形式时第一种形式的完整版
     print('a',end='') #end=‘‘可防止print打完后换行
     print() #空行

 

    for i in range(1,10):
        for j in range(1,i+1):
            print('%s*%s=%s'%(i,j,i*j),end='')
        print()

 

1*1=1

2*1=22*2=4

3*1=33*2=63*3=9

4*1=44*2=84*3=124*4=16

5*1=55*2=105*3=155*4=205*5=25

6*1=66*2=126*3=186*4=246*5=306*6=36

7*1=77*2=147*3=217*4=287*5=357*6=427*7=49

8*1=88*2=168*3=248*4=328*5=408*6=488*7=568*8=64

9*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81

 

    max_layer=5
    for current_layer in range(1, max_layer+1):
        for i in range(max_layer-current_layer):
            print(' ',end='')
        for j in range(2*current_layer-1):
            print('*',end='')
        print()

 

    *

   ***

  *****

 *******

*********

 

思考题:直角三角形,倒金字塔,棱形

 

二、元组

作用: 存多个值,只有读的功能,没有改的功能。在数据个数相同的情况下,使用元组更加节省空间;元组《列表《字典。对比列表来说,元组不可变(是可以当作字典的key的)。“元组就是一个不可变的列表”

 

定义: 与列表类型比,只不过把[]换成()

age1=(11,22,33,44,55)  #age=tuple((11,22,33,44,55))
(11, 22, 33, 44, 55)

 

print(tuple('hello'))  #换成range(10000)
print(list('hello'))

('h', 'e', 'l', 'l', 'o')

['h', 'e', 'l', 'l', 'o']

 

优先掌握的操作:

#1 按索引取值(正向取+反向取):只能取

#2 切片(顾头不顾尾,步长)

t=(1,2,3,4,5,6)
print(t[1:4])

 

(2, 3, 4)  #切出元组

 

# t=('a','b','c')
  t[0]=111   #报错,元组不可改,元组无append insert remove pop
 
t=('a','b','c','a')
print(t.index('b'))     #1
print(t.count('a'))     #2
 

#3长度

#4 成员运算in和not in

#5 循环

 

总结: 多个值,有序, 不可变,可做字典的key但不常用(dict的key不可重复)

 

三、购物车

msg_dic={'apple':10,'tesla':100000,'mac':3000,'lenovo':30000,'chicken':10,}
goods=[]
while True:
    for name in msg_dic:
        print('商品名:%s  价钱:%s'%(name,msg_dic[name]))
    good_name = input('商品名>>: ').strip()
    if good_name not in msg_dic:
        continue
   
price=msg_dic[good_name]
    while True:
        count=input('购买个数>>: ').strip()
        if count.isdigit():
            count=int(count)
            break
   
info={'good_name':good_name,'price':price,'count':count} #更简洁,方便取用
    goods.append(info)
    print(goods)

 

四、字典

作用:以key-value存取,可以存多个值,取值速度快, 每个值对应的key不能重复, 且key为不可变类型。缺点是浪费空间。

dic={(1,2,3):'aaa'}
print(dic)
print(dic[(1,2,3)])

 

{(1, 2, 3): 'aaa'}

aaa

 

dic={'x':1,'y':2,'x':3}
print(dic)    # {'x': 3, 'y': 2} 重复的key不报错,但后面的覆盖前面的

 

定义: key必须是不可变类型,value可以是任意类型

 

dic=dict(x=1,y=2,z=3)
print(dic)    # {'x': 1, 'y': 2, 'z': 3}

dic=dict({'x':1,'y':2,'z':3})
print(dic)  {'x': 1, 'y': 2, 'z': 3}

 

优先掌握的操作:

#1 按key存取值,可存可取

dic={'x':1,'y':2}
dic['age']=10
print(dic)       # {'x': 1, 'y': 2, 'age': 10}   直接加值

 

dic={'name':'egon'}
dic['name']=dic['name'].upper()
print(dici)    # {'name': 'EGON'}    字典为可变类型

 

#2 长度len

len() 可通用于有多个值的类型,对于字典,len返回的是键值对的个数

 

#3 成员运算in和not in

dic={'x':1,'y':2}
print('x' in dic)   #True   成员运算中dict判断的是key是否在字典中

 

#4 删除

  1. 可用del 万能删除
dic={'name':'egon','age':18}
del dic['name']
print(dic)     # {'age': 18}

 

  1. 可用pop,dict没有remove操作
dic={'name':'egon','age':18}
res=dic.pop('age')   # 18
print(dic)     # {'name': 'egon'}
    dic.pop('sex')    #报错
    
    dic.pop('sex','aaa') #若找不到,不报错,返回后一个参数值;一般用None
    print(dic.pop('sex','aaa'))  # aaa 

 

#5 **键keys(), 值values(), 键值对items()

dic={'name':'egon','age':18, 'sex':'male'}
print(dic.keys())
print(list(dic.keys()))
print(dic.values())
print(dic.items())

 

dict_keys(['name', 'age', 'sex'])     #不是列表,是一种特殊的类型

['name', 'age', 'sex']

dict_values(['egon', 18, 'male'])

dict_items([('name', 'egon'), ('age', 18), ('sex', 'male')])

 

dic={'name':'egon','age':18}
for value in dic.values():     egon \n 18
    print(value)

 

dic={'name':'egon','age':18}
print(dic.items())
for x in dic.items():
    print(x)
for k,v in dic.items():
    print(k,v)

 

('name', 'egon')

('age', 18)

name egon

age 18

#6 循环

 

字典要掌握的操作

dic={'name':'egon','age':18}
print(dic.get('name'))  #egon
print(dic.get('sex'))  #None, 根据key值取value,取不到返回None,不报错
print(dic['sex'])  #报错
print(dic.popitem())   # ('age', 18)  无参数,随机弹键值对,返回元组

 

dic={'name':'egon','age':18}
print(dic.update({'x':1,'age':19}))   # None
print(dic)   # {'name': 'egon', 'age': 19, 'x': 1}

#新字典有而老字典无的增加,新字典有而老字典也有的覆盖

 

dic={'name':'egon','age':18}
print(dic.setdefault('name', 'EGON'))   # egon
print(dic.setdefault('sex', 'male'))     # male

#字典中有key,则不修改,返回key对应的原值

 字典中没有key,则添加,返回添加的key的对应值

 

print({}.fromkeys(['name','age','sex'], None)) #快速造字典, 参数必须时seq序列类型(有序的:字符串,列表,元组), 顺序为空字典,先添加key,再添加value
good_info={'name':None,'age':None,'sex':None}
print(good_info)
good_info['count']=None
print(good_info)

 

{'name': None, 'age': None, 'sex': None}

{'name': None, 'age': None, 'sex': None}

{'name': None, 'age': None, 'sex': None, 'count': None}

 

{}.fromkeys() 等同于以下:

keys = ['name','age','sex']
dic={}
for key in keys:
    dic[key]= None
print(dic)

 

# python2 和 python3 中字典的小区别

python3 采取了底层优化机制使字典的输出看上去是有一定规律的,但字典时无序的

 

总结:

字典可存多个值,无序,可变

 

五、集合

作用:**关系运算,去重

 

定义:花括号内用逗号分隔的一个个元素

s={1,2,3,4,'a'}    # print(set({1,2,3,4,'a'}))s
print(s)         # {1, 2, 3, 4, 'a'}

 

注意的问题:

集合(无序)内没有重复的元素 =》去重

集合内元素必须时不可变类型

 

 

优先掌握的操作:

#1 长度len

#2 成员运算in和not in

#3 并集

s1={'alex','egon','ws','a'}
s2={'sal','alex','egon','b'}

print(s1|s2)
print(s1.union(s2))
 

{'a', 'egon', 'sal', 'alex', 'ws', 'b'}

 

#4 交集

print(s1&s2)
print(s1.intersection(s2))

 

{'egon', 'alex'}

 

不用集合的运算关系取交集的方法:

stu_linux=['alex','egon','ws','a']
stu_python=['sal','alex','egon','b']
stu_py_lx=[]
for stu in stu_linux:
    if stu in stu_python:
        stu_py_lx.append(stu)
print(stu_py_lx)

 

['alex', 'egon']

 

#5 差集

print(s1-s2)
print(s2-s1)
print(s1.difference(s2))
print(s1.difference(s2)

 

{'ws', 'a'}

{'b', 'sal'}

 

#6 交叉补集

print(s1^s2)
print(s1.symmetric_difference(s2))

 

{'sal', 'a', 'ws', 'b'}

 

#8父集、子集:谁包含谁 (了解)

s1={1,2,3}
s2={1,2}
print(s1>s2)   #True, 集合是无序的,所以集合之间不能比大小,这里的>是包含与被包含关系

#若s1==s2, s1和s2互为父子集

print(s1.issuperset(s2)) # True
print(s2.issubset(s1))    #True

 

#9 其他需掌握的操作

s1={1,2,3}
s1.update({3,4,5})   #可一次添加多值
print(s1)   # {1, 2, 3, 4, 5}

 

s1={1,2,3}
s1.add(4)   #添加元素,一次添加一个值
print(s1)    # {1, 2, 3, 4}

 

s1={1,2,3}
s1.difference_update({3,4}) #先做差值,然后更新原集合
print(s1)   # {1, 2}

 

s1={1,2,3}
s1.discard(3)
print(s1)   # {1, 2} 删除一个值,但该值不存在时什么都不做
s1.discard(4)
print(s1)   # {1, 2}.

 

s1={1,2,3}
s1.remove(3)
print(s1)  # {1, 2} 删除一个值,但该值不存在时报错
s1.remove(4)
print(s1)  #报错

 

s1={1,2,3}
s1.pop()
print(s1)    #{2, 3}, pop后无参数,随机取走一个值

 

s1={1,2,3}
print(s1.isdisjoint({1,2,4}))  #False, 是否无交集

 

s1={1,2,3}   #s1=set({1,2,3})
for item in s1:
    print(item)   # 1 /n 2 /n 3, 循环取值,查看

 

去重

  1. 去重,但顺序改变 (掌握)
l=['a','b',1,'a','a']
print(set(l))   #{1, 'b', 'a'}
print(list(set(l)))    #[1, 'b', 'a']

 

  1. 去重,且顺序不变(了解)
l=['a','b',1,'a','a']
l_new=[]
s=set()
for item in l:
    if item not in s:
        s.add(item)
        l_new.append(item)
print(l_new)    #['a', 'b', 1]

 

看解释:command

 

posted on 2018-08-11 17:16  2Maike  阅读(173)  评论(0编辑  收藏  举报