本文介绍了从列表中随机选择x个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写代码,该代码将在列表的1-4个元素之间随机选择50次.我正在使用的列表是['nu', 'ne', 'na', 'ku', 'ke', 'ka']
.
I am trying to write a code that will randomly select between 1 and 4 elements of a list 50 times. The list I am working with is ['nu', 'ne', 'na', 'ku', 'ke', 'ka']
.
所以从本质上讲,我希望它输出类似的内容
So essentially, I want it to output something like
nukuna
ke
keka
nuka
nane
nanenu
nu
nukekanu
kunu
...
50次
推荐答案
在Python中:
import random
input = [...] # Your input strings
output = ''
random.seed() # Seed the random generator
for i in range(0,len(input)):
N = 1+random.randrange(4) # Choose a random number between 1 and 4
for j in range(0,N): # Choose N random items out of the input
index = random.randrange(len(input)-j)
temp = input[index]
input[index] = input[len(input)-j-1]
input[len(input)-j-1] = temp
output += temp
output += ' '
print output
在C中
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
char* input[NUM_OF_INPUT_STRINGS] = {...}; // Your input strings
char output[MAX_SIZE_OF_OUTPUT+1];
// Seed the random generator
srand((unsigned int)time(NULL));
for (int i=0; i<NUM_OF_INPUT_STRINGS; i++)
{
// Set the output string empty
output[0] = 0;
// Choose a random number between 1 and 4
int N = 1+(rand()%4);
// Choose N random items out of the input
for (int j=0; j<N; j++)
{
int index = rand()%(NUM_OF_INPUT_STRINGS-j);
char* temp = input[index];
input[index] = input[NUM_OF_INPUT_STRINGS-j-1];
input[NUM_OF_INPUT_STRINGS-j-1] = temp;
strcat(output,temp);
}
// Print the output
printf("%s ",output);
}
这篇关于从列表中随机选择x个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!