我试图从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))]
我怎样才能做到这一点?
答案 0 :(得分:1)
首先,正如几位评论者提到的那样,您在问题上发布的输入是list
tuples
,而不是dict
。除此之外,要从集合中获取随机值,您可以使用python标准库中的random.choice,random.sample或random.choices。
您可以调用这样的函数:
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)
答案 1 :(得分:0)
首先,您需要将元组列表转换为字典:
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个随机密钥,请使用random.sample
:
import random
randomkeys = random.sample(d.keys(), 8)
要获取相应的值,您可以使用operator.itemgetter
:
import operator
randomvalues = operator.itemgetter(*randomkeys)(d)