Python - 列表中的随机范围
给定一个列表,从中提取随机范围。
Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Output : [5, 7, 2, 1]
Explanation : A random range elements are extracted of any length.
Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Output : [4, 8]
Explanation : A random range elements are extracted of any length.
方法:使用 randrange() + 切片
随机数(): Python提供了一个函数,可以从指定范围生成随机数,并且还允许包含步骤的空间,在random模块中称为randrange() 。
在这里,我们提取列表的索引,对于第一个索引,然后再次使用该函数使用randrange()从开始索引到列表长度获取范围的结束部分。范围是使用切片提取的。
Python3
# Python3 code to demonstrate working of
# Random range in list
# Using randrange() + slicing
import random
# function to Random range in list
def rabdomRangeList(test_list):
# getting ranges
strt_idx = random.randrange(0, len(test_list) - 1)
end_idx = random.randrange(strt_idx, len(test_list) - 1)
# getting range elements
res = test_list[strt_idx: end_idx]
return str(res)
# Driver Code
# initializing list
input_list1 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
# printing original list
print("\nThe original list is : ", input_list1)
# printing result
print("Required List : " + rabdomRangeList(input_list1))
# initializing list
input_list2 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
# printing original list
print("\nThe original list is : ", input_list2)
# printing result
print("Required List : " + rabdomRangeList(input_list2))
# initializing list
input_list3 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
# printing original list
print("\nThe original list is : ", input_list3)
# printing result
print("Required List : " + rabdomRangeList(input_list3))
输出:
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : [19]
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : [10, 13, 5, 7]
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : []