V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Feb 25, 2019 · 2869 views
    This topic created in 2625 days ago, the information mentioned may be changed or developed.

    需求如下: 两组数据: 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 replies    2019-02-26 00:08:11 +08:00
    TanLeDeDaNong
        1
    TanLeDeDaNong  
       Feb 25, 2019
    一次循环就完成的事,需要这么复杂? b 的结构太迷了,不能提出来 id:name 吗?
    bany
        2
    bany  
       Feb 25, 2019
    改用集合( set ),求一下交集?
    redial39
        3
    redial39  
       Feb 25, 2019
    x = dict(b)['t_id_{}'.format(id)].get('name',None) if dict(b).has_key(['t_id_{}'.format(id)]) else None

    瞎写的,没审题
    metamask
        4
    metamask  
       Feb 25, 2019
    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
       Feb 26, 2019
    @freakxx 这个确实简化了不少 另外结合求交集
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1214 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 352ms · UTC 17:11 · PVG 01:11 · LAX 10:11 · JFK 13:11
    ♥ Do have faith in what you're doing.