开发者

Fastest way to make a dict a single comma-separated string

开发者 https://www.devze.com 2022-12-28 15:28 出处:网络
I have a list of uids: [\'1234\',\'4321\',\'1111\'] and I would like to turn this into a single string of:

I have a list of

uids: ['1234','4321','1111'] 

and I would like to turn this into a single string of:

"uid = '1234' OR uid = '4321' OR u开发者_JAVA技巧id = '1111'"

What's the most efficient way to do this? Thanks!


' OR '.join("uid = '%s'" % u for u in uids)

This invokes the join function on the string ' OR ', which takes the list passed in and puts the string in between each element, then concatenates them all together. (Used to put the ORs in between each key=val pair.)

The part inside the () is a comprehension that says "for each u in the uids list, generate a value equal to the string "uid = '%s'", but substitute in u instead of the %s marker".


If—as Mike and Thomas mention in the comments—you need this for a database query, you should take Thomas' advice and use the DB-API.

Here are two examples:

MySQL

import MySQLdb
conn = MySQLdb.connect(host='localhost', user='u', passwd='p', db='mydb')
curs = conn.cursor()
uids = [1234,4321,1111]
qry = ("""SELECT cheese 
            FROM cheeseshop 
           WHERE id IN (%s)""" % ','.join(['%s']*len(uids)))
# 'SELECT cheese FROM cheeseshop WHERE id IN (%s,%s,%s)'
curs.execute(qry, uids)
curs.fetchone()
# ...

SQLite

import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
uids = [1234,4321,1111]
qry = ("""SELECT cheese 
            FROM cheeseshop 
           WHERE id IN (%s)""" % ','.join('?'*len(uids)))
# 'SELECT cheese FROM cheeseshop WHERE id IN (?,?,?)'
curs.execute(qry, uids)
curs.fetchone()
# ...
0

精彩评论

暂无评论...
验证码 换一张
取 消