如何将 n 个字符串元素的数组过采样为 m 个字符串元素的数组

How to oversample an array of n string elements into an array of m string elements

l 想将 n 个元素的数组过采样到 m 个元素的数组中,使得 m > n.

例如让我们取 n=3

colors=['red','blue','green']

设米=7

我在找什么?

 oversampled_colors=['green','blue','red','red','blue','green','blue']
import random
def fun(colors,n,m):
  colors1=[]
  while(len(colors1)<n):
      colors1.append(colors[random.randint(0,m-1)])
  return colors1
colors=['red','blue','green']
oversampled_colors=fun(colors,7,len(colors))
print(oversampled_colors)

np.random.choice 好像是你要找的

>>> colors=['red','blue','green']
>>> np.random.choice(colors, 7)
array(['red', 'red', 'green', 'red', 'blue', 'red', 'green'], dtype='<U5')

要采样 WITH 替换(值可以重复):

>>> random.choices(['red','blue','green'], k=5)
['green', 'green', 'red', 'blue', 'red']

此外,要采样 WITHOUT 替换(值不能重复):

>>> random.sample(['red','blue','green'], k=3)
['blue', 'green', 'red']