Random Choice 随机选择

# 1.1.5: Random Choice 随机选择

Often when we’re using numbers, but also,occasionally, with other types of objects,we would like to do some type of randomness.

For example, we might want to implement a simple random sampling process.

To this end, we can use the random module.

So the starting point is, again, to import that module, random.

Let’s think about a simple example where we have a set of numbers contained in a list,and we would like to pick one of those numbers uniformly at random.

The function we need to use in this case is random.choice,and inside parentheses, we need a list.

In this list, I’m going to just enter a few numbers– 2, 44, 55, and 66.

And then when I run the random choice, Python returns one of these numbers back to me.

If I repeat the same line, I’m going to get a different answer,because, again, Python is just picking one of those objects at random.

A crucial thing to understand about the random choice method is that Python doesn’t care about the fundamental nature of the objects that

are contained in that list.

What that means, instead of using numbers,I could also be choosing one out of several strings.

So let’s see how that might work.

I’m going to go back to my list.

I’m just going to include three short strings here.

Let’s just do “aa,” “bb,” and “cc.”

I can ask Python to pick one of these uniformly at random.

So Python doesn’t care about the nature of these objects.

Random works just the same way for any type of object.

上一篇
Modules and Methods 模块和方法
1.1.3: Modules and Methods 模块和方法让我们谈谈模块。Let’s talk a little bit about modules.Python模块是代码库，您可以使用import语句导入Python模块。Pytho
2021-10-18

Numbers and Basic Calculations 数字和基本计算
1.1.4: Numbers and Basic Calculations 数字和基本计算数字是Python中的一种对象类型。Numbers are one type of object in Python.实际上，Python提供了三种不
2021-10-18
目录