📜  随机创建N个K大小的列表的Python程序

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

随机创建N个K大小的列表的Python程序

给定一个列表,任务是编写一个Python程序来随机生成 N 个大小为 K 的列表。

例子:

方法 1:使用生成器+ shuffle()

在这种情况下,使用 shuffle() 来获取随机元素,并使用切片的产量来获得 K 大小的混洗列表。

Python3
# Python3 code to demonstrate working of
# K sized N random elements
# Using generator + shuffle()
from random import shuffle
  
# get random list 
def random_list(sub, K):
    while True:
        shuffle(sub)
        yield sub[:K]
  
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
  
# initializing K, N 
K, N = 3, 4
               
# printing original list
print("The original list is : " + str(test_list))
  
res = []
# getting N random elements 
for idx in range(0, N):
    res.append(next(random_list(test_list, K)))
  
# printing result
print("K sized N random lists : " + str(res))


Python3
# Python3 code to demonstrate working of
# K sized N random elements
# Using product() + sample()
from random import sample
import itertools
  
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
  
# initializing K, N 
K, N = 3, 4
               
# printing original list
print("The original list is : " + str(test_list))
  
# get all permutations
temp = (idx for idx in itertools.product(test_list, repeat = K))
  
# get Random N from them
res = sample(list(temp), N)
res = list(map(list, res))
  
# printing result
print("K sized N random lists : " + str(res))


输出:

The original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[7, 1, 8], [8, 6, 1], [4, 9, 6], [6, 9, 1]]

方法 2:使用product() + sample()

在这种情况下,使用 product() 提取 K 个元素的所有可能排列,并从 N 个列表中随机抽样完成。

蟒蛇3

# Python3 code to demonstrate working of
# K sized N random elements
# Using product() + sample()
from random import sample
import itertools
  
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
  
# initializing K, N 
K, N = 3, 4
               
# printing original list
print("The original list is : " + str(test_list))
  
# get all permutations
temp = (idx for idx in itertools.product(test_list, repeat = K))
  
# get Random N from them
res = sample(list(temp), N)
res = list(map(list, res))
  
# printing result
print("K sized N random lists : " + str(res))

输出:

The original list is : [6, 9, 1, 8, 4, 7]
K sized N random lists : [[1, 1, 1], [6, 9, 4], [8, 7, 6], [4, 8, 8]]