Random number-----Random in Python

Source: Internet
Author: User
Tags shuffle

These methods are located in the random module

Random.random (), Math.random () with JavaScript, returns a floating-point number between [0.0,1)

Random.uniform (A, B), returns the floating-point number between [a,b]

The Python code print random.uniform # print Random.uniform #----results (different results on various machines) #18.7356606526 #12.5798298022

Random.randint (A, B), returns the integer Python code print random.randint #生成的随机数n between [a,b]: <= n <= print random. Randint #结果永远是20 #print random.randint (#该语句是错误的). The lower bound must be less than the upper limit.

Random.randrange ([start], stop[, step] gets a random number from the specified range, in the set incremented by the specified cardinality. such as: Random.randrange (10, 100, 2), the result is equivalent from [10, 12, 14, 16, ... 96, 98] sequence to obtain a random number.

Random.randrange (10, 100, 2) are equivalent to Random.choice (range (10, 100, 2) on the results. Random.choice (Sequence). The parameter sequence represents an ordered type. Here's how: sequence is not a specific type in Python, it's a series of types. list, tuple, strings belong to sequence.

Print Random.choice ("Learning python") Python code print Random.choice (["Jgood", "is", "a", "handsome", "boy"]) print ran Dom.choice ("Tuple", "List", "Dict"))

Random.shuffle (x[, random]), used to disrupt elements in a list

Python code p = [Python, ' is ', ' powerful ', ' simple ', ' and so on ... '] Random.shuffle (p) Print P #----results (different The results on the machine may not be the same. #[' powerful ', ' simple ', ' are ', ' Python ', ' and so on ... ']

Random.sample (sequence, k) that randomly obtains a fragment of the specified length from the specified sequence. The sample function does not modify the original sequence.

Python code list = [1, 2, 3, 4, 5, 6, 7, 8, 9,] slice = random.sample (list, 5) #从list中随机获取5个元素, return print as a fragment Slice Print List #原有序列并没有改变.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.