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

2024-06-16 11:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在阅读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


Tags: ofthetothat场景notitdo
3条回答

这取决于您希望使用for .. in循环访问每个键的随机值的有限列表还是无限列表。你知道吗

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

对于每个键都有一个“无限”列表的情况,它实际上并不存在(除非你有无限的内存……),你应该为每个键创建一个生成器,而不是一个list。你知道吗

谷歌python generator你会得到所有需要的文档,让你开始。你知道吗

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

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

相关问题 更多 >