Python List创建字典问题~
PHP中文网
PHP中文网 2017-04-17 13:23:29
0
3
402
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
刘奇

is actually impossible to construct. The dictionary key-value pair needs to be uniquely corresponding. End

小葫芦
dict(zip(l1, l2))
伊谢尔伦

Because your l1 is shorter than l2, and you want l1 to be the key of the dictionary, and l2 to be the value of the dictionary, this will cause a problem: fewer keys correspond to more Values ​​are used to form a dictionary, which will inevitably result in the keys in l1 needing to be reused, but this conflicts with the non-repeatable keys of the dictionary, because two “a” keys are not allowed in a dictionary.
Of course, if it is the other way around, with l2 as the key and l1 as the value, this problem does not exist, for example, it forms:

{1:'a', 2:'b', 3:'c', 4:'a', 5:'b', 6:'c'}

is absolutely no problem. To achieve this, you can write:

dict(zip(l2,len(l2)//len(l1)*l1+l1[0:len(l2)%len(l1)]))

# 这是在 python 3.x 下的写法,如果是 py 2.x 请将 '//' 写成 '/'

Run result:

{1: 'a', 2: 'b', 3: 'c', 4: 'a', 5: 'b', 6: 'c'}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template