1 #encoding=utf-8 2 3 4 5 #反转字典 即key和val互换 6 dict1={1:2,3:4,6:7,9:10} 7 8 9 print ‘---生成器表达式‘ 10 def invert_dict(d): 11 return dict((v,k) for k,v in d.iteritems()) 12 13 print invert_dict(dict1) 14 15 16 print ‘---列表推导‘ 17 def invert_dict2(d): 18 return dict([(v,k) for k,v in d.iteritems()]) 19 20 print invert_dict2(dict1) 21 22 23 print ‘---itertools 提高大数据效率‘ 24 from itertools import izip 25 26 27 def invert_dict3(d): 28 return dict(izip(d.itervalues(),d.iterkeys())) 29 30 print invert_dict3(dict1)
打印结果如下:
---生成器表达式
{2: 1, 4: 3, 10: 9, 7: 6}
---列表推导
{2: 1, 4: 3, 10: 9, 7: 6}
---itertools 提高大数据效率
{2: 1, 4: 3, 10: 9, 7: 6}
时间: 2024-11-08 18:19:15