Home  >  Article  >  Backend Development  >  How to avoid duplication of random elements in python

How to avoid duplication of random elements in python

(*-*)浩
(*-*)浩Original
2019-08-02 09:59:343872browse

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]

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!

Statement:
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