首页 > 解决方案 > 如何从 Python 列表中弹出多个随机元素?

问题描述

每当我从中采样时,我都会尝试从原始列表中删除元素。

list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)

当我np.random.choice,我想list_a成为一个没有元素的列表list_b

标签: python

解决方案


这可以使用 python 的 remove() 来完成。

您可以在此处阅读有关 remove() 的更多信息:https ://www.programiz.com/python-programming/methods/list/remove

import numpy as np
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)

for i in list_b:
    list_a.remove(i)

print list_a
print list_b

结果:

list_a = [a, c]
list_b = [b, d]

推荐阅读