通过随机数据流在列表中的字典

Dictionary within a list through a random data stream

我正在阅读 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 a loop
  • At present I can do it statically i.e. by hard-coding it but that does not take me anywhere

有人可以帮我吗?

P.S. This is not a homework question

您可以使用 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)的范围是可选的,您可以更改它!

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

这取决于您是否希望使用 for .. in 循环访问每个键的随机值的有限列表,或者无限列表。

对于有限列表的情况,给出的答案很好。

对于每个键 "infinite" 列表的情况,它实际上并不存在(除非你有无限量的内存......),你应该创建一个 generator 每个键,而不是 list.

Google python generator 您将获得开始所需的所有文档。