元祖,字典

五 元组

复制代码
#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读

#定义:与列表类型比,只不过[]换成()
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))

#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取   
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in

#5、循环
复制代码

  练习

复制代码
#简单购物车,要求如下:
实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} 
复制代码
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
    for key,item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item,name=key))
    choice=input('商品>>: ').strip()
    if not choice or choice not in msg_dic:continue
    count=input('购买个数>>: ').strip()
    if not count.isdigit():continue
    goods_l.append((choice,msg_dic[choice],count))

    print(goods_l)
View Code

六 字典

复制代码
#作用:存多个值,key-value存取,取值速度快

#定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)

#优先掌握的操作:
#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in

#4、删除
#5、键keys(),值values(),键值对items()
#6、循环
复制代码

  练习

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
复制代码
a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
    if i>66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)
复制代码
View Code
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
复制代码
s='hello alex alex say hello sb sb'

l=s.split()
dic={}
for item in l:
    if item in dic:
        dic[item]+=1
    else:
        dic[item]=1
print(d

猜你喜欢

转载自www.cnblogs.com/zhangsongbei/p/9119800.html
今日推荐