我从Python教程上读到了有关字典的内容,并遇到了以下情况:“
['x','y','z',.....]{'x':[0,0,70,100,...] , 'y':[0,20,...] , ...}的dictionarydynamically,即使用loopstatically,也就是通过hard-coding,但这不会带我去任何地方有人能帮我吗?
P.S. This is not a homework question
发布于 2015-01-04 07:56:22
import random # To generate your random numbers
LOW = 0 # Lowest random number
HIGH = 100 # Highest random number
NUM_RANDS = 5 # Number of random numbers to generate for each case
l = ['x', 'y', 'z'] # Your pre-existing list
d = {} # An empty dictionary
for i in l: # For each item in the list
# Make a dictionary entry with a list of random numbers
d[i] = [random.randint(LOW, HIGH) for j in range(NUM_RANDS)]
print d # Here is your dictionary如果这令人困惑,您可以将行d[i] = [random...替换为:
# Create a list of NUM_RANDS random numbers
tmp = []
for j in range(NUM_RANDS):
tmp.append(random.randint(LOW,HIGH))
# Assign that list to the current dictionary entry (e.g. 'x')
d[i] = tmp发布于 2015-01-04 07:49:26
您可以使用random和列表理解:
>>> import random
>>> l=['x','y','z']
>>> r_list_length=[4,10,7]
>>> z=zip(r_list_length,l)
>>> {j:[random.randint(0,100) for r in xrange(i)] for i,j in z}
{'y': [39, 36, 5, 86, 28, 96, 74, 46, 100, 100], 'x': [71, 63, 38, 11], 'z': [8, 100, 24, 98, 88, 41, 4]}random.randint(0,100)的范围是可选的,您可以更改它!
发布于 2015-01-04 08:16:34
这取决于您是否希望使用for .. in循环来访问每个键的随机值的有限列表,或无限的随机值列表。
对于有限列表的情况,给出的答案是很好的。
对于每个键都不存在的“无限”列表(除非您有无限大的内存.),您应该每个键创建一个生成器,而不是创建一个list。
谷歌python生成器,你会得到所有必要的文件,让你开始。
https://stackoverflow.com/questions/27763504
复制相似问题