python中元组列表中的随机值
我试图从python中的以下输入类型中获得一些随机的5或8个值python中元组列表中的随机值,python,Python,我试图从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.3
[(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))]
我如何才能得到它?首先,您需要将元组列表转换为字典:
l = [(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))]
d = dict(l)
要获得8个随机键,请使用:
要获取相应的值,可以使用:
首先,正如几位评论者所提到的,您在问题上发布的输入是
元组的列表,而不是dict
。除此之外,要从集合中获取随机值,可以使用:,或从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)
import operator
randomvalues = operator.itemgetter(*randomkeys)(d)
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)