我是靠谱客的博主 靓丽乌冬面,最近开发中收集的这篇文章主要介绍mysql字典表的映射关系,将Mysql元组重新映射到字典,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Hello

I want to convert a Mysql resulset to a dictionary.

I made some code myself, and want to ask you if I do this the right way.

def remapmysql(a):

return (a[0], (a[1:]))

def test_map():

count = 100000 # count of simulated records

l1 = range(0, count)

l2 = range(count , 2 * count )

l3 = range(2 * count, 3 * count )

z1 = zip(l1, l2, l3) # simulate a mysql resultset

d1 = dict(map(remapmysql,z1))

return d1

解决方案Pom wrote:

I want to convert a Mysql resulset to a dictionary.

that is, you want to convert an array of (key, value, ...) tuples to a

dictionary containing key: (value, ...) pairs, right ?

I made some code myself, and want to ask you if I do this the right way.

def remapmysql(a):

return (a[0], (a[1:]))

def test_map():

count = 100000 # count of simulated records

l1 = range(0, count)

l2 = range(count , 2 * count )

l3 = range(2 * count, 3 * count )

z1 = zip(l1, l2, l3) # simulate a mysql resultset

d1 = dict(map(remapmysql,z1))

return d1

looks fine to me.

if you care about performance, and is using a recent Python, you could

try doing

d1 = dict((row[0], row[1:]) for row in z1)

instead, and see if that runs faster (this uses a generator expression

instead of a callback and a full list).

def remapmysql(a):

return (a[0], (a[1:]))

def test_map():

count = 100000 # count of simulated records

l1 = range(0, count)

l2 = range(count , 2 * count )

l3 = range(2 * count, 3 * count )

z1 = zip(l1, l2, l3) # simulate a mysql resultset

d1 = dict(map(remapmysql,z1))

return d1

I''m not sure the map() is needed, as it could just be

>>d1 = dict((row[0], row[1:]) for row in z1)

which worked in my tests.

However either seems to work fairly well.

-tkc

Fredrik Lundh wrote:

if you care about performance, and is using a recent Python, you could

yes i do ;-)

try doing

d1 = dict((row[0], row[1:]) for row in z1)

instead, and see if that runs faster (this uses a generator expression

instead of a callback and a full list).

I changed it and it saves me some time so I leave it like that!

with 100000 test records:

>>>

dict+map (1, 2, 3) -{1: (2, 3)}: 1.343 seconds.

dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 0.861 seconds.

>>>

dict+map (1, 2, 3) -{1: (2, 3)}: 1.397 seconds.

dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 0.943 seconds.

with 500000 test records:

>>>

dict+map (1, 2, 3) -{1: (2, 3)}: 13.297 seconds.

dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 8.335 seconds.

>>>

dict+map (1, 2, 3) -{1: (2, 3)}: 14.548 seconds.

dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 9.793 seconds.

>>>

thank you!!

最后

以上就是靓丽乌冬面为你收集整理的mysql字典表的映射关系,将Mysql元组重新映射到字典的全部内容,希望文章能够帮你解决mysql字典表的映射关系,将Mysql元组重新映射到字典所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部