首页 > 解决方案 > 从列表中删除单个项目

问题描述

所以我试图定义 Draw(n= int),但是当我运行这段代码时,命令 self.contents.remove(r),它只返回 1 个项目。而且我在画画的时候需要把球从桶里拿出来,所以我不会两次得到同一个球。

class Bucket:
    def __init__(self, **kwargs):
        self.contents = []
        for k,v in kwargs.items():
            for n in range(v):
                self.contents.append(k)

    def draw(self, n):
        x = []
        for ball in range(n):              
            r = random.choice(self.contents)
            x.append(r)
            self.contents.remove(r)
                
        if n > len(self.contents):
            return self.contents
        else: return x

h1 = Hat(red=3,blue=2)
print(h1.contents)
print(h1.draw(4))

输出是:

['red', 'red', 'red', 'blue', 'blue']
['blue'] ---> this supposed to have 4 items.

这里有什么问题?

标签: pythonlist

解决方案


问题是最后的if测试。如果您从 中删除至少一半的项目self.contents,则为n > len(self.contents)真,您将返回self.contents而不是x.

如果您试图防止错误尝试绘制比 中的更多的球self.contents,则if条件应该在函数的开头,而不是结尾。

def draw(self, n):
    if n > len(self.contents):
        x = self.contents
        self.contents = []
    else:
        x = []
        for ball in range(n):              
            r = random.choice(self.contents)
            x.append(r)
            self.contents.remove(r)
            
    return x

推荐阅读