免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1570 | 回复: 2
打印 上一主题 下一主题

python list用法求教 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-12-16 14:23 |只看该作者 |倒序浏览
遇到这个情况,写的代码好麻烦,有没有简介的写法看起来更pythonic的?

  1. tuple_list = [(1,2,3),(4,5,6)]
  2. des_list = ('name','type','description')

  3. dict_tmp = {}
  4. ret_list = []
  5. for t in tuple_list:
  6.         for x,y in zip(t,des_list):
  7.                 dict_tmp[y] = x
  8.         ret_list.append(dict_tmp)
  9.         dict_tmp = {}
复制代码

论坛徽章:
4
金牛座
日期:2013-10-11 16:12:50卯兔
日期:2014-07-31 09:17:19辰龙
日期:2014-08-08 09:28:02狮子座
日期:2014-09-14 20:32:05
2 [报告]
发表于 2014-12-16 16:00 |只看该作者
  1. In [1]: tuple_list = [(1,2,3),(4,5,6)]

  2. In [2]: des_list = ('name','type','description')

  3. In [3]: ret_list = [dict(zip(des_list, each)) for each in tuple_list]

  4. In [4]: ret_list
  5. Out[4]:
  6. [{'type': 2, 'name': 1, 'description': 3},
  7. {'type': 5, 'name': 4, 'description': 6}]

  8. In [5]:
复制代码

论坛徽章:
0
3 [报告]
发表于 2014-12-16 17:52 |只看该作者
本帖最后由 feihuadao 于 2014-12-16 17:52 编辑

get it!!:wink::wink::wink:

回复 2# ssfjhh
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP