简体   繁体   中英

How to generate a list of lists with random numbers of the same length

How do you generate a random list of lists? I can generate a random list using the following [random.sample(range(80), 20)] .

You can use the * function to make it list of lists but the numbers aren't random for each list. I can find answers relating to the creation of random list of lists that produce variable lengths but I can't find anything that will produce random numbers with the same length.

Here's one way, assuming that you want several random samples of the same kind.

First, for neatness, not necessity, curry random.sample using functools partial so that it produces, for the sake of this example, a sample of size 5 from the integers from 0 through 9 inclusive, each time it's called.

Then simply use list comprehension to produce a collection of those samples.

>>> import random
>>> from functools import partial
>>> one_sample = partial(random.sample, range(10), 5)
>>> one_sample()
[2, 8, 0, 5, 6]
>>> sample = [one_sample() for _ in range(3)]
>>> sample
[[9, 6, 7, 2, 0], [5, 8, 9, 6, 7], [5, 0, 6, 7, 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