拆分后您有一个列表,您可以对该列表进行切片以获取子列表:
for prod_emp in prodemployees:
prod_emp = prod_emp.split()
prod, emp = prod_emp[0], prod_emp[1:]
这里prod
设置为拆分字符串的第一个元素,emp
除了第一个元素之外的所有元素的列表:
>>> prodemployees = ['prd1 employe4 employe2', ' prd2 employe2']
>>> for prod_emp in prodemployees:
... prod_emp = prod_emp.split()
... prod, emp = prod_emp[0], prod_emp[1:]
... print prod, emp
...
prd1 ['employe4', 'employe2']
prd2 ['employe2']
从现在开始,我将使用 SQL 参数来执行实际查询。构建过滤器,然后将所有拆分参数链作为一个长参数列表传递:
from itertools import chain
filters = filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
cursor.execute('SELECT * FROM sometable WHERE {}'.format(
' OR '.join(filters)),
chain.from_iterable(pe.split() for pe in prodemployees))
这里filters
使用参数占位符生成合适的 SQL:
>>> filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
>>> list(filters)
['(product=%s AND employee in (%s, %s))', '(product=%s AND employee in (%s))']
>>> filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
>>> 'SELECT * FROM sometable WHERE {}'.format(
... ' OR '.join(filters))
'SELECT * FROM sometable WHERE (product=%s AND employee in (%s, %s)) OR (product=%s AND employee in (%s))'
这.execute()
将从chain.from_iterable()
提供的参数中填写您的查询:
>>> list(chain.from_iterable(pe.split() for pe in prodemployees))
['prd1', 'employe4', 'employe2', 'prd2', 'employe2']
此处使用的%s
占位符特定于某些类型的数据库适配器;其他人可以?
改用;检查您的数据库适配器文档。