例如,如果我有一个 1x100 数组,它包含 90 个 0,我想以某种方式排除随机选择的 80 个 0。我已经为这个问题苦苦挣扎了一段时间,不幸的是我几乎没有取得任何进展。
3 回答
2
香草 Python 方法。
确定满足条件的元素的索引:
candidate_indices = [i for i, x in enumerate(data) if data == 0]
选择要删除的索引:
removed_indices = random.sample(candidate_indices, 80)
通过构建一个没有相应元素的列表来删除它们:
result = [x for i, x in enumerate(data) if i not in removed_indices]
于 2020-07-23T02:12:20.917 回答
2
因为你有一个numpy标签:
import numpy as np
def solution(arr, value, size):
return np.delete(arr, np.random.choice(np.flatnonzero(arr==value), size, False))
arr = np.array([0]*90 + [1]*10)
np.random.shuffle(arr)
print(solution(arr, 0, 80)) # [1 0 1 0 0 1 0 0 1 0 1 1 1 0 0 0 0 1 1 1]
print(solution(arr, 0, 90)) # [1 1 1 1 1 1 1 1 1 1]
print(solution(arr, 0, 100)) # Raises error (expected behavior)
于 2020-07-23T00:56:45.287 回答
1
这是一种方法,它不是很有效,但它应该是健壮的。
def progressivelyExcludeItem(item, arr, maxExclusions):
"""
@param item the item value that will be progressively excluded
@param arr the list from which we will exclude
@param maxExclusions the maximum number of excluded items
"""
excludeIndices = [i for i, x in enumerate(arr) if x == item]
excludeIndices = random.shuffle(excludeIndices)[:maxExclusions]
for i in excludeIndices.sort().reversed():
arr.pop(i)
时间复杂度为 O(n^2)。
于 2020-07-23T00:13:57.347 回答