我在阅读Python Tutorial的词典时遇到了以下场景”
- Let us say , that there exists a list :
['x','y','z',.....]
- I wish to generate a random data stream for each of the elements of the above list i.e. I want a
dictionary
like :{'x':[0,0,70,100,...] , 'y':[0,20,...] , ...}
- I wish to do this task
dynamically
i.e. using aloop
- At present I can do it
statically
i.e. byhard-coding
it but that does not take me anywhere
有人能帮我吗?
P.S. This is not a homework question
这取决于您希望使用
for .. in
循环访问每个键的随机值的有限列表还是无限列表。你知道吗对于有限列表的情况,给出的答案很好。你知道吗
对于每个键都有一个“无限”列表的情况,它实际上并不存在(除非你有无限的内存……),你应该为每个键创建一个生成器,而不是一个
list
。你知道吗谷歌python generator你会得到所有需要的文档,让你开始。你知道吗
如果混淆了这一点,可以将
d[i] = [random...
行替换为:您可以使用
random
和列表理解:random.randint(0,100)
的范围是可选的,您可以更改它!你知道吗相关问题 更多 >
编程相关推荐