简体   繁体   English

从列表中随机选择 x 个元素

[英]Randomly select x number of elements from a list

I am trying to write a code that will randomly select between 1 and 4 elements of a list 50 times.我正在尝试编写一个代码,该代码将在列表的 1 到 4 个元素之间随机选择 50 次。 The list I am working with is ['nu', 'ne', 'na', 'ku', 'ke', 'ka'] .我正在使用的列表是['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 times 50次

In Python:在 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

In C:在 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);
}

Try with this Python code:试试这个 Python 代码:

import random

my_list = ['nu', 'ne', 'na', 'ku', 'ke', 'ka']

for i in xrange(0,50):
    tmp_string = ''
    count = random.randrange(1,4)      # choose a random between 1 and 4
    for j in xrange(0, count):
         # add a random member of the list to the temporary string
         tmp_string = tmp_string + random.choice(my_list)
    print tmp_string         # print each final string

this is the easiest way to do it in python这是在python中最简单的方法

from random import randint, choice

input_list = ['nu', 'ne', 'na', 'ku', 'ke', 'ka']


for x in range(50): (print "".join([choice(input_list) for x in range(randint(1,4))]))
int i=0;
StringBuffer stb=new StringBuffer();
String[] arr= {"nu", "ne", "na", "ku", "ke", "ka"};
while(i<50){
int idx = new Random().nextInt(arr.length);
 stb.append(arr[idx]);

i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM