生成随机数作为python

时间:2016-10-17 21:31:44

标签: python dictionary random

请问您能告诉我如何生成一个包含100行的字典,每行中0到1之间的随机数作为值?例如,在数据框中,我可以:

   df['Rand'] = random.sample(random.random(), 100)

但我不知道如何为字典做这件事。

2 个答案:

答案 0 :(得分:7)

我认为你想要的是:

{k: random.random() for k in range(100)}

答案 1 :(得分:0)

首先,它应该是list而不是dict。检查:In Python, when to use a Dictionary, List or Set?

为了获取值列表,您可以使用 list comprehension

>>> import random
>>> row_count = 10
>>> my_list = [random.random() for i in range(row_count)]
# Value of 'my_list':
# [0.9158936600374181, 0.8998648755500501, 0.07002867165493243, 0.6694284854833131, 0.4903966580363698, 0.9462143737260301, 0.8014661448602305, 0.47964245438139297, 0.42326131297319725, 0.77540761767324]

为了获取第5个项目(即第4个索引):

>>> my_list[4]
0.4903966580363698