[英]Fastest way to make a dict a single comma-separated string
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 uid = '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. 这将在字符串' OR '
上调用join
函数,该函数接收传入的列表并将字符串放入每个元素之间,然后将它们全部串联在一起。 (Used to put the ORs in between each key=val pair.) (用于将OR置于每个key = val对之间。)
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". ()
的部分是一个理解,表示“对于uids
列表中的每个u
,生成一个等于字符串"uid = '%s'"
,但用u
代替%s
标记”。
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 . 如Mike和Thomas在评论中提到的那样,如果您需要数据库查询,则应该听Thomas的建议并使用DB-API 。
Here are two examples: 这是两个示例:
MySQL 的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 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()
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.