用Python创建具有列表理解功能的字典我喜欢Python列表理解语法。它也能用来创建字典吗?例如,通过对键和值的对进行迭代:mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work
3 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
{key: value for (key, value) in iterable}
dict
dict((key, func(key)) for key in keys)
dict
# consumed from any iterable yielding pairs of keys/valsdict(pairs)# "zipped" from two separate iterables of keys/valsdict (zip(list_of_keys, list_of_values))
九州编程
TA贡献1785条经验 获得超4个赞
实际上,如果迭代已经包含了某种映射,那么甚至不需要对迭代进行迭代,DECT构造函数为您做得很好:
>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}
添加回答
举报
0/150
提交
取消