Python:动态拆分列表

时间:2013-06-18 14:41:42

标签: python python-2.7

我有一个列表prodemployees,如下所示:

['prd1 employe4 employe2', ' prd2 employe2']

我需要此列表的值来动态创建查询的“where”语句,我需要输出如下:

WHERE (product = 'prd1' AND employe IN ('employe4','employe2'))
OR
(product = 'prd2' AND employe IN ('employe2'))

我尝试在列表的每个值上拆分空白,并创建一个包含结果值的子列表,但未能使用这些值。

我是Python的新手,感谢任何帮助。

splitOnSpace = []
for i in range(len(prodemployees)) :
  splitOnSpace = prodemployees[i].split()
    for j in range(len(splitOnSpace)) : 
       #this is where I should do something with splitOnSpace[j] I guess...

1 个答案:

答案 0 :(得分:7)

分割后您有一个列表,您可以切片该列表以获取子列表:

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占位符特定于某些类型的数据库适配器;其他人可能会使用?;检查数据库适配器文档。