V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
haoxuexiaoyao
V2EX  ›  Python

数据库查询出一组数据,如何查询降低匹配次数

  •  
  •   haoxuexiaoyao · 2019-02-25 14:05:12 +08:00 · 1768 次点击
    这是一个创建于 1858 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求如下: 两组数据: goods 数据是数据库查询出来的一组数据,

    goods = Pay.query.filter_by(state=4).all()
    good_ids = []
    for good in goods:
    	good_ids.append(good['id'])
    

    b 数据是其他地方获取的数据:

    b = {
    	"t_id_1": {
    		id = "1",
    		name = 'name1'
    	},
    	"t_id_2": {
    		id = "2",
    		name = 'name2'
    	},
    	"t_id_3": {
    		id = "3",
    		name = 'name3'
    	},
    	"t_id_4": {
    		id = "4",
    		name = 'name4'
    	},
    	"t_id_5": {
    		id = "5",
    		name = 'name5'
    	},
    	"t_id_6": {
    		id = "6",
    		name = 'name6'
    	},
    	"t_id_7": {
    		id = "7",
    		name = 'name7'
    	}
    }
    

    如果 goods_id 中有的 数字和 b 里面的 id 数字对应,输出 对应的 name,这个如何操作比较好啊,我的方式如下:

    for item in b:
    	for good_id in good_ids:
        	if good_id == b[item]['id']:
            	print(b[item]['name'])
    

    请教下如何一次性比较后一次性输出打印结果比较好呢. 我的写法好啰嗦

    5 条回复    2019-02-26 00:08:11 +08:00
    TanLeDeDaNong
        1
    TanLeDeDaNong  
       2019-02-25 15:28:43 +08:00
    一次循环就完成的事,需要这么复杂? b 的结构太迷了,不能提出来 id:name 吗?
    bany
        2
    bany  
       2019-02-25 15:31:57 +08:00
    改用集合( set ),求一下交集?
    redial39
        3
    redial39  
       2019-02-25 15:47:38 +08:00
    x = dict(b)['t_id_{}'.format(id)].get('name',None) if dict(b).has_key(['t_id_{}'.format(id)]) else None

    瞎写的,没审题
    freakxx
        4
    freakxx  
       2019-02-25 17:32:59 +08:00
    good_ids = [good['id'] for good in goods]

    names = [item["name"] for item in b.values() if item["id"] in good_ids]
    haoxuexiaoyao
        5
    haoxuexiaoyao  
    OP
       2019-02-26 00:08:11 +08:00
    @freakxx 这个确实简化了不少 另外结合求交集
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3089 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:51 · PVG 20:51 · LAX 05:51 · JFK 08:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.