How to avoid duplication of random elements in python

(*-*)浩
Release: 2019-08-02 09:59:34
Original
3900 people have browsed it

Python can avoid duplication of random elements by using the sample() function of the random module, which returns a new list that stores random non-repeating elements.

How to avoid duplication of random elements in python

Function usage example: (Recommended learning: Python video tutorial)

range() range can only be integers

random.sample(population, k)

Returns a k-length list of unique elements selected from the overall sequence or collection (potution) (list). The new list stores random non-repeating elements. Used for random sampling without replacement.

import random

list = [1, 2, 3]
print(random.sample(list ,2))

list = ["china","python","sky"]
print(random.sample(list ,2))

list = range(1, 10000)
print(random.sample(list ,5))

输出:
[1, 2]
['python', 'sky']
[6912, 1869, 5991, 721, 3388]
Copy after login

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to avoid duplication of random elements in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!