如何编写将列表添加到字典的函数?

2024-05-13 11:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

忙碌的程序员在这个美好的社区。你知道吗

我正试图完成一本书中的一项任务,这本书名叫《自动化无聊的东西》。在这里,我试图将这个dragonLoot[]列表附加到itemsSatchel{}字典中。我尝试使用这个更新属性,在我把列表改成字典之后,但是失败了,所以我真的不知道该怎么办。救命啊!你知道吗

import pprint

itemsSatchel = {'Arrow': 12,
                'Gold Coin': 42,
                'Rope': 1,
                'Torch': 6,
                'Dagger':1}

dragonLoot = ['Gold Coin',
              'Gold Coin'
              'Dagger'
              'Gold Coin',
              'Ruby']

def addToSatchel(self):
    #This part is my pain in the ___#


def displaySatchel(self):
    print("Inventory: ")
    itemsCounter = 0
    for k,v in itemsSatchel.items() :
        pprint.pprint(str(v) + ' ' + str(k))
        itemsCounter += v
    print('Total number of items: ' + str(itemsCounter))

addToSatchel({dragonLoot})

displaySatchel(itemsSatchel)

Tags: inself列表字典defpprintcoinstr
3条回答

尝试遍历数组中的元素,如果字典中存在相同元素,则将其值增加1;如果不存在,则仅设置1。你知道吗

像这样:

# Hello World program in Python
import pprint

itemsSatchel = {'Arrow': 12,
                'Gold Coin': 42,
                'Rope': 1,
                'Torch': 6,
                'Dagger':1}

dragonLoot = ['Gold Coin',
              'Gold Coin',
              'Dagger',
              'Gold Coin',
              'Ruby']

def addToSatchel():
    for item in dragonLoot:
        if item in itemsSatchel:
            itemsSatchel[item] += 1
        else:
            itemsSatchel[item] = 1 

def displaySatchel():
    print("Inventory: ")
    itemsCounter = 0
    for k,v in itemsSatchel.items() :
        pprint.pprint(str(v) + ' ' + str(k))
        itemsCounter += v
    print('Total number of items: ' + str(itemsCounter))

addToSatchel()

displaySatchel()

干杯!你知道吗

您还可以考虑在这里使用^{}。它可以从dict或项目列表中初始化或更新。你知道吗

from collections import Counter

itemsSatchel = Counter({'Arrow': 12,
                        'Gold Coin': 42,
                        'Rope': 1,
                        'Torch': 6,
                        'Dagger':1})

dragonLoot = ['Gold Coin', ...]

def addToSatchel(items):
    itemsSatchel.update(items)

addToSatchel(dragonLoot)

首先,去掉“self”参数,这不是一个类方法,而是一个函数编程。 现在,如果我没听错的话,你可以试着做一些事情,比如:

def addToSatchel():
    for el in dragonLoot:
        itemsSatchel[el] = itemsSatche.setdefault(el, 0) + 1    

def displaySatchel():
    ...
    ...

电话应该是:

addToSatchel()
displaySatchel()

相关问题 更多 >