Get the App
SLTechnology News&Howtos  ›  Development  › 

How to randomly sample elements from list by python

Shulou Source: shulou.com Published: 2022-06-01 04:34:49 09月22日 Update

This article mainly shows you "python how to randomly sample elements from list", the content is easy to understand, clear, hope to help you solve doubts, the following let Xiaobian lead you to study and learn "python how to randomly sample elements from list" this article.

How to randomly sample elements from list

Import randomall_data = [num for num in range (100)] sample_data = random.sample (all_data, 20) print sample_data# [71, 25, 58, 79, 70, 69, 93, 29, 11, 30, 40, 81, 12, 48, 91, 21, 83, 42, 38, 31]

Here, 20 elements are randomly sampled from 100 elements. As you can see, the sampling function can be easily realized with the help of the sample function of random module. Python random module is very interesting, you can see if you are interested, can achieve a lot of interesting functions. For example, you can easily achieve the "shuffle" function:

Import randomorder_list = range (10) print order_list# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle (order_list) print order_list# [3, 5, 9, 0, 8, 7, 1, 2, 6, 4] are all the contents of the article "how python randomly samples elements from list". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Elements content functions articles modules learning help fun interesting interest functions easy to understand more organization knowledge editing industry information information channels channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Xiaomi Shulou Tech Info NVidia macOS