我正在尝试从 python 中的以下输入类型中获取一些随机的 5 或 8 个值
[(1, (0.0, 1.1)), (2, (0.0, 2.21)), (3, (0.0, 3.31)), (5, (0.0, 4.41)),
(5,(0.0, 5.51)), (6, (0.0, 6.62)), (7, (0.0, 7.72)), (8, (0.04, 0.0)),
(9, (0.04, 1.1)), (10, (0.04, 2.21)), (11, (0.04, 2.21)), (12, (0.04, 3.31)),
(13, (0.04, 3.31)), (14, (0.04, 4.41))]
我怎样才能得到它?
请您参考如下方法:
首先,正如一些评论者提到的,您在问题中发布的输入是 元组 的列表,而不是dict。除此之外,要从集合中获取随机值,您可以使用:random.choice , random.sample或 random.choices来自 python 标准库。
你可以这样调用函数:
import random
your_input = [(1, (0.0, 1.1)), (2, (0.0, 2.21)), (3, (0.0, 3.31)),
(5, (0.0, 4.41)), (5,(0.0, 5.51)), (6, (0.0, 6.62)),
(7, (0.0, 7.72)), (8, (0.04, 0.0)), (9, (0.04, 1.1)),
(10, (0.04, 2.21)), (11, (0.04, 2.21)), (12, (0.04, 3.31)),
(13, (0.04, 3.31)), (14, (0.04, 4.41))]
# Let's take one random number
one_choice = random.choice(your_input)
# Let's sample 10 random numbers from the list without replacement
n_samples = random.sample(your_input, k=10)
# Let's take 10 random numbers from the list **with** replacement
n_samples = random.choices(your_input, k=10)
