用简易代码快速学习Python(四)

本学习系列介绍:

本学习系列主要针对对编程略有了解有其他语言基础并要进一步学习Python的同学,通过简易的代码快速入门掌握Python语言。

系列总目录:
用简易代码快速学习Python(一)
用简易代码快速学习Python(二)
用简易代码快速学习Python(三)
用简易代码快速学习Python(四)
用简易代码快速学习Python(五)
用简易代码快速学习Python(六)
用简易代码快速学习Python(七)
用简易代码快速学习Python(八)
用简易代码快速学习Python(九)
用简易代码快速学习Python(十)

今天内容较少,但请深入理解。

Day04:

递归:

汉诺塔问题:

count= 0
def hanoi(n, x, y, z):
    global count
    if n==1:
        count += 1
        print('第', count, '步:将', n, '号木块从', x, '移动到', z, '上')
    else:
        hanoi(n-1, x, z, y)
        count += 1
        print('第', count, '步:将', n, '号木块从', x, '移动到', z, '上')
        hanoi(n-1, y, x, z)

n = int(input("请输入汉诺塔层数:"))
hanoi(n, 'A', 'B', 'C')
print('结论:%d层的汉诺塔移动一共需要用 %d 步' % (n, count))

字典:

注意:字典是没有顺序的、可改变的。

字典的标识为{}。

dict() -> new empty dictionary

dict(mapping) -> new dictionary initialized from a mapping object’s (key, value) pairs

dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

例如:

dict1 = {'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
print(dict1) #输出:{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
dict1 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
print(dict1) #输出:{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
dict1 = dict(a='aaa',b='bbb') #注意:此时字符串作为key时不用引号。
print(dict1) #输出:{'a': 'aaa', 'b': 'bbb'}
dict1['c'] = 'ccc' #若索引在字典中未出现,可以直接添加到字典中。
print(dict1) #输出:{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}
dict1 = {'a':'haha'}
dict1 = dict1.fromkeys(range(5), '赞')
print(dict1) #输出:{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}

print(dict1[6]) #报错,因为key不存在。
print(dict1.get(3)) #输出:赞
print(dict1.get(6)) #输出:None
print(dict1.get(3, 'good')) #输出:赞
print(dict1.get(6, 'good')) #输出:good
a = {'name':'lxy'}
b = a
print(b) #输出:{'name':'lxy'}
a = {}
print(b) #输出:{'name':'lxy'}

a = {'name':'lxy'}
b = a
print(b) #输出:{'name':'lxy'}
a.clear()
print(b) #输出:{}
a = {'name':'lxy'}
b = a.copy()
c = a
print(id(a)) #输出a的地址
print(id(b)) #输出b的地址,与a的地址不同。
print(id(c)) #输出c的地址,与a的地址相同。
a = {'name':'lxy', 'age':20}
b = {'age':23, 'id':123456}
a.update(b)
print(a) #输出:{'name': 'lxy', 'age': 23, 'id': 123456}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘学长丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值