字典:求和计数(return知识巩固)
2021/8/9 6:08:13
本文主要是介绍字典:求和计数(return知识巩固),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
野餐用品计数
之前写过一段,字符在字符串中出现次数的代码
import pprint message = 'It was a bright cold day in April, ' \ 'and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] += 1 pprint.pprint(count)
在写野餐用品计数代码时,发现多了个return
由于一直对于返回值的概念不甚了解,又把两段代码拿出来做了对比
并且把野餐用品代码拆分后,每个判断后加上print来查看流程及参数值
发现如果不用return给totalBrought()设一个返回值,
那当apple = totalBrought(allGuests,‘apples’)时,就没有一个值可以返回给apple
由此对return又多了点了解
原代码是没有apple=这一句的,直接用
print("Apples: " + str(totalBrought(allGuests, 'apples')))
来替代了Apples打印行
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {"ham sandwiches": 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item): numBrought = 0 for k, v in guests.items(): numBrought = numBrought + v.get(item, 0) return numBrought apple = totalBrought(allGuests, 'apples') print("Number of things being brought:") print("Apples: " + str(apple)) print("Cups: " + str(totalBrought(allGuests, 'cups'))) ...
=================================
物品清单统计:
1. 一开始写,很呆滞,每个物品单独一个打印语句
2. 还把return写倒了total行同缩进,导致返回的数值一直是1,修改后:
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def totalitem(allItems): total = 0 for k, v in allItems.items(): total = allItems.get(k, 0) + total return total items = totalitem(inventory) print('Inventory:' + "\n" + str(inventory['arrow']) + ' arrow' + "\n" + str(inventory['gold coin']) + ' gold coin' + "\n" + str(inventory['rope']) + ' rope' + "\n" + str(inventory['torch']) + ' torch' + "\n" + str(inventory['dagger']) + ' dagger' + "\n" + 'Total number of items: ' + str(items))
3. 参考了提示并整合后,打印加入到循环中
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print('Inventory') total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) total += v print('Total number of items:' + str(total)) displayInventory(inventory)
============
假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
写一个名为 addToInventory(inventory, addedItems)的函数,
其中 inventory 参数是一个字典,表示玩家的物品清单(像前面项目一样),
addedItems 参数是一个列表,就像 dragonLoot。
addToInventory()函数应该返回一个字典,表示更新过的物品清单。
def displayInventory(inventory): print('Inventory') total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) total += v print('Total number of items:' + str(total)) def addToInventory(inventory, addedItems): for k in addedItems: if k in inventory.keys(): inventory[k] += 1 else: inventory[k] = 1 return inventory inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
1. 开始想到将列表转换成字典,再将两个字典比较后拼接
2. 若字典中不存在key,则可用dic[key]=value来增加键值对
3. 两个字典相加:相同key,值相加;不同key,值保留
dica = {'a': 1, 'b': 2, 'c': 3, 'f': "hello"} dicb = {'b': 3, 'k': 'world'} dic = {} for key in dica: if dicb.get(key): dic[key] = dica[key] + dicb[key] else: dic[key] = dica[key] for key in dicb: if dica.get(key): pass else: dic[key] = dicb[key] print(dic)
4. 起初代码一直如下,试了很久v+=1,但v的值始终无变化(其实是混淆了v和dic[k]的意义,v并不是dic[k])
重看定义:key()、values()、items()方法返回的值是元组,即不可变(设定如此,其实是搅屎棍,变不变的都无所谓)
因为k,v只是字典在使用方法时返回的值(返回的键值值赋值给了变量k,v),所以即使修改变量v的值,对字典本身的值是不起作用的
5. 所以需要循环累加字典内键的值,必须用dict[k]+=1
dictA = {'a': 1, 'b': 42} listB = ['b', 'c', 'b'] for i in listB: for k, v in dictA.items(): print(i, k, v, dictA[k]) v += 1 # × # dictA[k] += 1 # √
这篇关于字典:求和计数(return知识巩固)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南