向词典添加和删除条目(&s)

2024-05-20 18:43:56 发布

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

我正在处理这个练习,我只是在字典中循环键,向set添加条目,并从字典中删除条目。你知道吗

根据官方文件,这一准则应将其削减:

import random

BITES = {6: 'PyBites Die Hard',
     7: 'Parsing dates from logs',
     9: 'Palindromes',
     10: 'Practice exceptions',
     11: 'Enrich a class with dunder methods',
     12: 'Write a user validation function',
     13: 'Convert dict in namedtuple/json',
     14: 'Generate a table of n sequences',
     15: 'Enumerate 2 sequences',
     16: 'Special PyBites date generator',
     17: 'Form teams from a group of friends',
     18: 'Find the most common word',
     19: 'Write a simple property',
     20: 'Write a context manager',
     21: 'Query a nested data structure'}
BITES_DONE = {6, 10, 16, 18, 21}


class NoBitesAvailable(Exception):
    print(Exception)


class Promo:

    def __init__(self, bites=BITES, bites_done=BITES_DONE):
        self.bites = bites
        self.bites_done = bites_done

    def _pick_random_bite(self):
        keys = []
        for key in self.bites.keys():
            keys.append(key)
        random_key = random.choice(keys)
        #print(random_key)
        return random_key

    def new_bite(self):
        try:
            this_bite = self._pick_random_bite()
            if this_bite not in self.bites_done:
                self.bites_done.add(this_bite)
                del self.bites[this_bite]
            else:
                del self.bites[this_bite]

        except:
            raise NoBitesAvailable()

a = Promo()
a.new_bite()
print(a._pick_random_bite())
print(a.bites_done)
print(a.bites)

所发生的是,似乎由于某种原因,if - else条件被完全忽略了。你知道吗

我试图在这里实现的是,从字典中随机选取一个键,如果该键位于名为“BITES\u DONE”的集合中,则将其从字典中删除,但是,如果该键不在集合中,则将其添加到集合中,然后将其从字典中删除。你知道吗

有什么建议吗?你知道吗


Tags: keyinself字典bitesrandomkeysthis
1条回答
网友
1楼 · 发布于 2024-05-20 18:43:56

我在我的机器上也试过,效果很好。问题是您看到的random_bite与实际删除的random_bite不同。你知道吗

当您调用a.new_bite()时,它会调用第一个_pick_random_bite();当您调用print(a._pick_random_bite())时,它很可能与新的^位调用中随机位的结果不同。你知道吗

为了简单地检查结果,您可以在new_bite方法中移动随机咬合的打印。你知道吗

如下所示:

class Promo:
    def __init__(self, bites=BITES, bites_done=BITES_DONE):
        self.bites = bites
        self.bites_done = bites_done

    def _pick_random_bite(self):
        return random.choice(self.bites.keys())

    def new_bite(self):
        this_bite = self._pick_random_bite()
        print(this_bite) # Print the actual random_bite
        if this_bite not in self.bites_done:
            self.bites_done.add(this_bite)
        self.bites.pop(this_bite, None)

a = Promo()
a.new_bite()
print(a.bites_done)
print(a.bites)

相关问题 更多 >