gpt4 book ai didi

dynamic - 是否可以在 Python 脚本中生成和执行 Python 代码? [动态 Python 代码]

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:35 32 4
gpt4 key购买 nike

我正在处理一些报告(计数),我必须获取不同参数的计数。非常简单但乏味。

一个参数的示例查询:

qCountsEmployee = (
"select count(*) from %s where EmployeeName is not null"
% (tablename)
)
CountsEmployee = execute_query(qCountsEmployee)

现在我有几百个这样的参数!

我所做的是:创建所有参数的列表并使用快速 Python 脚本生成它们,然后复制该文本并将其放入主脚本中以避免繁琐的行。

columnList = ['a', 'b', ............'zzzz']

for each in columnList:
print (
'q' + each + ' ='
+ '"select count(*) from %s where' + each
+ 'is not null" % (tablename)'
)
print each + ' = execute_query(' + 'q' + each + ')'

虽然这种方法有效,但我想知道是否可以直接在主脚本中生成它们并让脚本将它们视为代码行,而不是使用单独的脚本来生成代码行并将它们复制粘贴到主程序中?我认为这将使代码更具可读性。希望我说得有道理!谢谢...

最佳答案

这是可能的,但在这里没有用。

只是做类似的事情

columnList = ['a', 'b', ............'zzzz']

results = {}
for column in columnList:
query = (
"select count(*) from " + tablename
+ " where " + column + " is not null"
)
result = execute_query(qCountsEmployee)
results[column] = result

您也可以将所有这些放在一个生成器函数中并执行

def do_counting(column_list):
for column in column_list:
query = (
"select count(*) from " + tablename
+ " where " + column + " is not null"
)
result = execute_query(qCountsEmployee)
yield column, result

result_dict = dict(do_counting(['...']))

关于dynamic - 是否可以在 Python 脚本中生成和执行 Python 代码? [动态 Python 代码],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231384/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com