首页 > 解决方案 > 从列表中随机选择这些数字的百分比

问题描述

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%)

我怎样才能做到这一点?

标签: pythonarraysnumpy

解决方案


如果我理解正确,这就是你想要的:

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)


推荐阅读