2017-10-19 104 views
0

我有一个list我想转换为dictionary并将相应的随机values添加到它们,尝试以前的答案在这里似乎没有任何工作。将列表转换为字典并向它们添加值

这是list

wordlist = ["apple","durian","banana","durian","apple","cherry", 
      "cherry","mango","apple","apple","cherry","durian","banana", 
      "apple","apple","apple","apple","banana","apple"] 

用简单的语法有答复将不胜感激。

+3

什么*转换为Python *意味着什么?你拥有的'list'已经是一个有效的Python'list'。不需要转换。你的问题总体上很不好解释。 –

+0

你是什么意思'我想转换成python'? – Harman

+0

Think OP意思是'dictionary' –

回答

0

Incase,OP正在寻找一个dictionary(想想h e是),只是做:

>>> import random 
>>> d = {} 
>>> for key in set(wordlist):      #note use of `set` 
     d[key] = random.randint(0,1000)   #the (beg,end) value is your choice 

>>> d 
=> {'apple': 816, 'mango': 342, 'banana': 231, 'durian': 765, 'cherry': 186} 

否则,如果他想在tuple与值列表,只是做:

>>> l = [] 
>>> for key in wordlist: 
     l.append((key,random.randint(0,1000))) 

>>> l 
=> [('apple', 645), ('durian', 4), ('banana', 451), ('durian', 550), ('apple', 772), 
    ('cherry', 800), ('cherry', 972), ('mango', 448), ('apple', 783), ('apple', 433), 
    ('cherry', 733), ('durian', 210), ('banana', 656), ('apple', 196), ('apple', 25), 
    ('apple', 395), ('apple', 98), ('banana', 589), ('apple', 695)] 

#driver值

IN : wordlist = ["apple","durian","banana","durian","apple","cherry", 
       "cherry","mango","apple","apple","cherry","durian","banana", 
       "apple","apple","apple","apple","banana","apple"] 
+0

谢谢你回答我的问题, –

-1

不是太难的问题。只需要导入numpy来获得随机值。

import numpy as np 

wordlist = ["apple","durian","banana","durian","apple","cherry", "cherry","mango","apple","apple","cherry","durian","banana", "apple","apple","apple","apple","banana","apple"] 

values = [np.random.random() for x in range(len(wordlist)] 
d = {*zip(wordlist,values)} 
print (d) 

{( '樱桃',0.9664602705758596),( '樱桃',0.42093671361304286),( '樱桃',0.6516552865418069),( '苹果',0.09858653336142964),( '香蕉',0.3976892252830715),(”苹果',0.9495323589015604),('apple',0.8118746084650151),('apple',0.3174994273783074),('banana',0.04230289240363949),('apple',0.35558531683946804),('durian',0.09960999590643527) ('apple',0.5284715524820693),('apple',0.38801846246977323),('banana',0.5548286775310872),('mango',0.5978643178837114),('durian',0.8401078154686553),('apple',0.7398063632475643) ),('apple',0.6945371327360194)}

+2

这是一套,而不是一本字典。为什么你会用这个Numpy?只需导入'random'并直接调用它的函数。 –