📜  从Python列表中随机选择 n 个元素

📅  最后修改于: 2022-05-13 01:55:08.305000             🧑  作者: Mango

从Python列表中随机选择 n 个元素

在本文中,我们将讨论如何在Python中从列表中随机选择 n 个元素。在继续讨论这些方法之前,让我们讨论一下我们将在我们的方法中使用的随机模块。
随机模块:
随机模块是Python中预定义的模块,它包含返回随机值的方法。当我们想要生成随机值时,这个模块很有用。 Random 模块的一些方法是:-
seed()getstate()choice()sample()等。

让我们讨论实现这一点的不同方法。
方法 1:使用sample()方法。 sample()方法用于从给定序列中返回所需的项目列表。此方法不允许序列中的重复元素。

# importing random module
import random
  
# declaring list
list = [2, 2, 4, 6, 6, 8]
  
# initializing the value of n
n = 4
  
# printing n elements from list
print(random.sample(list, n))

输出 :

[8, 6, 6, 4]

方法2:使用choice()方法。 choice()方法用于从给定序列中返回一个随机数。序列可以是列表或元组。这会从考虑序列(列表)中重复值的可用数据中返回单个值。

# importing random module
import random
  
# declaring list
list = [2, 2, 4, 6, 6, 8]
  
# initializing the value of n
n = 4
  
# traversing and printing random elements
for i in range(n):
      
    # end = " " so that we get output in single line
    print(random.choice(list), end = " ")

输出 :

8 2 4 6