首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表中随机选择x个元素

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

Stack Overflow用户
提问于 2014-01-18 01:44:36
回答 4查看 1.1K关注 0票数 1

我正在尝试写一个代码,它将随机选择列表中的1到4个元素50次。我使用的列表是['nu', 'ne', 'na', 'ku', 'ke', 'ka']

所以从本质上讲,我希望它输出类似这样的内容

代码语言:javascript
复制
nukuna
ke
keka
nuka
nane
nanenu
nu
nukekanu
kunu
...

50次

EN

回答 4

Stack Overflow用户

发布于 2014-01-18 02:13:47

Python中的

代码语言:javascript
复制
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:中的

代码语言:javascript
复制
#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);
}
票数 1
EN

Stack Overflow用户

发布于 2014-01-20 06:33:43

尝试使用以下Python代码:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2020-01-29 03:22:39

这是在python中执行此操作的最简单方法。

代码语言:javascript
复制
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))]))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21192435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档