Python程序选择随机值形式的列表列表
给定一个列表列表。任务是从中提取一个随机元素。
例子:
Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Output : 7
Explanation : Random number extracted from Matrix.
Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]], r_no = 2
Output : 6
Explanation : Random number extracted from 2nd row from Matrix.
方法#1:使用chain.from_iterable() + random.choice()
在此,我们使用 from_iterable() 将矩阵展平为列表,并且使用choice() 从列表中获取随机数。
Python3
# Python3 code to demonstrate working of
# Random Matrix Element
# Using chain.from_iterables() + random.choice()
from itertools import chain
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# choice() for random number, from_iterables for flattening
res = random.choice(list(chain.from_iterable(test_list)))
# printing result
print("Random number from Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Random Matrix Element
# Using random.choice() [if row number given]
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = 1
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[r_no])
# printing result
print("Random number from Matrix Row : " + str(res))
输出
The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix : 6
方法#2:使用choice()从特定行获取元素
如果提到一行,则可以使用choice() 方法从该行中获取随机元素。
Python3
# Python3 code to demonstrate working of
# Random Matrix Element
# Using random.choice() [if row number given]
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = 1
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[r_no])
# printing result
print("Random number from Matrix Row : " + str(res))
输出
The original list is : [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
Random number from Matrix Row : 7