python - 从列表中删除单个项目
问题描述
所以我试图定义 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.
这里有什么问题?
解决方案
问题是最后的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
推荐阅读
- orientdb - 在服务器端函数中将字符串转换为 ORecordId
- html - 在 Jquery 制作的 Snake 游戏中计算分数
- python - sympy 是否有内置方法来设置多个多项式彼此相等?
- scala - 为什么在推断类型构造函数时不使用所有类型边界?
- linux - 为 Linux 内核构建完整的控制流图
- google-sheets - 雅虎财经获得增长率
- javascript - 如何在不丢失编译时类型安全的情况下将 [一些嵌套输入对象] 转换为 [Generic 1] 到 [Generic 2]?
- node.js - 使用 firebase 托管的网页仅返回内部服务器错误
- c++ - 为什么返回指向没有 malloc 初始化的结构的指针在 C++ 中不会失败
- machine-learning - 当我用 tensorflow 2.0 训练 VGG 时,为什么我的准确率没有提高,只保持在 25% 左右