将列表转换为字典并向其添加值

时间:2017-10-19 13:06:39

标签: python

我有list我要转换为dictionary并向其添加相应的随机values,尝试之前的答案似乎没有任何效果。

这是list

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

任何使用简单语法的答案都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

Incase,OP正在寻找dictionary(认为他是),只是这样做:

>>> 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 value

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

答案 1 :(得分:-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)

{(' cherry',0.9664602705758596),(' cherry',0.42093671361304286),(' cherry',0.6516552865418069),(' apple&# 39;,0.09858653336142964),(' banana',0.3976892252830715),(' apple',0.9495323589015604),(' apple',0.8118746084650151),(' apple',0.3174994273783074),(' banana',0.04230289240363949),(' apple',05558531683946804),(' durian',0.09960999590643527),(&# 39; durian',0.2164173276423449),(' mango',0.5978643178837114),(' durian',0.8401078154686553),(' apple',0.7398063632475643),( ' apple',0.5284715524820693),(' apple',0.38801846246977323),(' banana',0.5548286775310872),(' apple',0.6945371327360194) }