python日记----2017.7.20

一丶默写

1
将两个变量的值交换顺序
x = 1
b = 2
x ,b= b ,x
print(x,b)
2
从[1, 2, 3, 4, 5, 6, 7]
取出第一个值和最后两个值
L =[1, 2, 3, 4, 5, 6, 7]
print(L[0],L[-2:])
3
循环打印如下字典的key和value
msg_dic = {
'apple': 10,
'tesla': 1000000,
'mac': 3000,
'lenovo': 30000,
'chicken': 10,
}
for i in msg_dic:
print(i,msg_dic[i])

4
用append + pop模拟队和堆栈
用insert + pop模拟队列和堆栈
堆栈:
l = []
l.append('1')
l.append('2')
l.append('3')
print(l)
l.pop()
print(l)
l.pop()
print(l)
l.pop()
print(l)
l = []
l.append('1')
l.append('2')
l.append('3')
print(l)
l.pop(0)
print(l)
l.pop(0)
print(l)
l.pop(0)
print(l)
5
循环取字典的key
循环取字典的value
循环取字典的items


msg_dic = {
'apple': 10,
'tesla': 1000000,
'mac': 3000,
'lenovo': 30000,
'chicken': 10,
}
for x in msg_dic.keys():
print(x)

for y in msg_dic.values():
print(y)

for x,y in msg_dic.items():
print(x,y)

二丶作业

作业一:
打印99乘法表

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

print(' ')




作业二:简单购物车

实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
msg_dic = {
'apple': 10,
'tesla': 100000,
'mac': 3000,
'lenovo': 30000,
'chicken': 10,
}

作业三:字典练习
  1
有如下值集合[11, 22, 33, 44, 55, 66, 77, 88, 99, 90...],将所有大于
66
的值保存至字典的第一个key中,将小于
66
的值保存至第二个key的值中。(2
分)

  即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

msg = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
info_dic = dict.fromkeys(('k1','k2','k3'),[])
for i in msg:
num = 66
if i > 66:
info_dic.setdefault('k1', []).append(i)
elif i < 66:
info_dic.setdefault('k2', []).append(i)
else:
info_dic.setdefault('k3', []).append(i)
print(info_dic)

a=[11,22,33,44,55,66,77,88,99,90,80,70,60,50,40,30,20,10]
# b=dict.fromkeys(('k1','k2'),[])
b = {}
c = []
d = []
for i in a:
if i>66:
d.append(i)
b.setdefault('k1',[d])
print(b)
if i<66:
c.append(i)
b.setdefault('k2',[c])
print(b)


  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'
a = s.split()
b={}
for i in a:
# b.setdefault(i, [a.count(i)])
b.setdefault(i,[]).append(a.count(i))
print(b)

原文地址:https://www.cnblogs.com/De-Luffy/p/7213962.html