【发布时间】:2019-08-25 22:25:21
【问题描述】:
每当我从中采样时,我都会尝试从原始列表中删除元素。
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
当我np.random.choice 时,我希望list_a 是一个没有list_b 元素的列表。
【问题讨论】:
标签: python
每当我从中采样时,我都会尝试从原始列表中删除元素。
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
当我np.random.choice 时,我希望list_a 是一个没有list_b 元素的列表。
【问题讨论】:
标签: python
您可以打乱列表然后拆分它,为您提供采样的元素和剩余的元素。
import numpy as np
list_a = ["a", "b", "c", "d"]
np.random.shuffle(list_a)
list_b, list_a = list_a[:2], list_a[2:]
【讨论】:
您可以有一个列表排除存在于list_b 中的list_a 的元素:
使用列表推导:
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
print([x for x in list_a if x not in list_b])
print(list_b)
输出:
['c', 'd']
['b' 'a']
【讨论】:
这可以使用 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]
【讨论】:
>>> import numpy as np
>>> list_a = ["a", "b", "c", "d"]
>>> _ = [list_a.remove(i) for i in np.random.choice(list_a, 2) if i in list_a]
>>> list_a
['b', 'd']
【讨论】:
然后使用choice 函数,您可以获得一个随机整数作为索引并在列表中使用pop():
import random
list_a = ["a", "b", "c", "d"]
def select_and_remove(list, items):
sample = []
for i in range(0, items)
sample.append(list.pop(random.randint(0, len(list)-1))
return list, sample
然后运行:
list_a, sample = select_and_remove(list_a, 2)
但是请注意,如果列表为空或您想选择更多可用的项目,这将抛出 ValueError
【讨论】: