简体   繁体   中英

How do I create 5 lists of 5 random numbers selected from a list?

From a list of numbers, I'd like to randomly create 5 lists of 5 numbers.

import random

def team():
    x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 
    y = []
    Count = 0
    count = 0
    while Count < 5:
        while count<5:
            count += 1
            z = random.choice(x)
            y += z
            x.remove(z)
        print(y)
        Count +=1

team()

Output:

在此处输入图片说明

Expected Output:

I want something like 5 groups of non-repeating numbers

change the code to

import random

def team():
    Count = 0
    while Count < 5:
        x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        y = []
        count = 0
        while count<5:
            count += 1
            z = random.choice(x)
            y += z
            x.remove(z)
        print(y)
        Count +=1

team()

in fact, for your original code, the count becomes 5 and break the second for loop. but next time, your count is still 5 , so it doesn't go into the second for loop.

You just print the first got y five 5 times.:)

This is a one-liner if you use a nested list comprehension. Also we can just directly sample the integers 0..9 instead of your list of string ['0', '1',...,'9']

import random

teams = [[random.randrange(10) for element in range(5)] for count in range(5)]

# Here's one example run: [[0, 8, 5, 6, 2], [6, 7, 8, 6, 6], [8, 8, 6, 2, 2], [0, 1, 3, 5, 8], [7, 9, 4, 9, 6]]

or if you really want string output instead of ints:

teams = [[str(random.randrange(10)) for element in range(5)] for count in range(5)]

[['3', '8', '2', '5', '3'], ['7', '1', '9', '7', '9'], ['4', '8', '0', '4', '1'], ['7', '6', '5', '8', '2'], ['6', '9', '2', '7', '3']]

or if you really want to randomly sample an arbitrary list of strings:

[ random.sample(['0','1','2','3','4','5','6','7','8','9'], 5) for count in range(5) ]

[['7', '1', '5', '3', '0'], ['7', '1', '6', '2', '8'], ['3', '0', '9', '7', '2'], ['5', '1', '7', '3', '2'], ['6', '2', '5', '0', '3']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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