python - 从列表中随机选择这些数字的百分比
问题描述
import random
import numpy as np
x = np.random.randint(1,101,100)
x
Output:
array([ 87, 50, 89, 99, 17, 29, 33, 17, 29, 64, 3, 80, 93,
30, 97, 99, 69, 28, 13, 32, 18, 95, 40, 75, 30, 47,
96, 67, 40, 12, 68, 69, 39, 93, 70, 73, 63, 12, 27,
91, 58, 89, 37, 2, 47, 66, 42, 72, 73, 64, 6, 21,
91, 83, 70, 69, 61, 11, 5, 46, 28, 25, 53, 10, 100,
93, 36, 66, 6, 31, 54, 95, 19, 97, 16, 80, 61, 5,
27, 29, 65, 55, 77, 71, 23, 71, 2, 95, 25, 29, 3,
78, 74, 1, 92, 95, 100, 20, 55, 75])
我想随机选择这些数字中的 25% 来附加 y。y=? (长度(x)*25%)
我怎样才能做到这一点?
解决方案
如果我理解正确,这就是你想要的:
import random
import numpy as np
x = np.random.randint(1,101,100)
_25_percent = int(len(x)/4) # 100/4 = 25; 25% of 100
_25_percent_list = random.sample(list(x), _25_percent) #<class 'list'>
np_array = np.array(_25_percent_list) #<class 'numpy.ndarray'>
print(np_array)
推荐阅读
- python - MetPy suface_based_cape_cin 返回带有单位的错误
- javascript - 格式化要在 Vue.js 组件中使用的 laravel 路由字符串
- javascript - 如何在javascript子类中调用父方法
- javascript - 排毒匹配器在本地工作,但在 Circle CI 上失败
- c# - C# 在一行中将多个元素添加到 IList - AddRange 不可用
- reactjs - 未找到模块:您尝试导入项目 src/ 目录之外的模块
- php - 使用递归函数从多维数组中返回随机值的字符串值
- typescript - TypeScript 泛型声明语法
- python - 如果两个类扩展不同的类,如何避免重复代码
- python-3.x - 输入函数的正确上下文使用是什么?它是否具有定义函数的任何功能?