首页 > 解决方案 > 根据数组中的项目数在 Python 中使用 % 进行字符串输入

问题描述

我正在用 python 编写功能,它使用 itertools.combinations 来生成基于另一个项目数组的组合数组。这个新数组用于根据数组中的项目数提供 SQL 查询。组合的分组(itertools.combinations 中的 r 值)是一个动态值。

 array = [1,2,3,4,5,6,7,8,9,0]
 arrayDerived = list(combinations(array,2))

arrayDerived = [[1,2],[1,3] .....[9,0]]

根据组合中的项目数量,我将调整 SQL 查询。

query = 'select * from %s where '
n= NoInCombination
x=1
while x < n:
    query = query + " %s =\'x\' AND"
    x =x+1
while x==n:
    query = query + " %s =\'x\'"
    x=x+1

构建查询后,如何根据 %s 的动态量正确指定字符串(下面代码的 D 部分)

前任:

 for d in arrayDerived:
     cur.execute(query%(TABLE_NAME,D))

标签: pythonmysqlstringdata-scienceitertools

解决方案


推荐阅读