需要把含有元组元素的列表转换为dict用什么方法,元素dict,比如下面这种的:list
需要把含有元组元素的列表转换为dict用什么方法,元素dict,比如下面这种的:list
比如下面这种的:
list = [ (a, 1), (a, 2), (c, 3), (d, 4), (d, 5), (f, 6)]
转换成下面这种
dict = { 'a': [1, 2], 'c': 3, 'd': [4, 5], 'f': 6}
方法一:dt = {}for (m,n) in ls: dt.setdefault(m,[]).append(n)方法二:from collections import defaultdictdt = defaultdict(list)for (m,n) in ls: dt.append(n)
ps:上面ls->list,dt->dict,最终得到结果和你的稍微有点不同,是dt的值的都是list。另外你list里a应该是'a',其他类似。
编橙之家文章,
相关内容
- 请教python实现socket数据接受转发问题,pythonsocket,serve
- virtualbox虚拟机与本地主机相互访问要怎么设置?,vi
- Python tornado Linux系统平台, 是实现了Epoll模型, 还是会使
- python导入其它目录中模块方法是什么,python模块,这个模
- 为什么 Python Flask sqlalchemy数值如果太大时会出错呢,
- Python赋值方式不同,效果为什么也不同?,python赋值方式
- apache 32位服务器,python 2.77出现error R6034怎么解决?,2.7
- 列表里边是元组数据,用python正则怎么完成匹配,pytho
- python精度误差如何控制?,python精度误差,Python 2.7.9
- python包管理 返回报错ProtocolError:是何问题,,python包管理
评论关闭