You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过函数参数动态调整SELECT查询结果的打印字段数量?

这问题我碰到过好多次,其实只要给函数加个灵活的参数,就能轻松解决硬编码字段的问题,给你几个实用的方案:

解决方案1:添加可选字段索引参数(兼容原有行为)

我们可以给函数新增一个fields_to_print参数,默认值设为你原来的[0,1,3],这样用户不传这个参数时,函数就和原来一样工作;需要打印不同字段(或不同数量)时,传一个自定义的索引列表就行。

修改后的函数代码:

def print_query_result(con, query, fields_to_print=None):
    # 没传参数时,使用默认的字段索引
    if fields_to_print is None:
        fields_to_print = [0, 1, 3]
    con.execute(query)
    for row in con:
        # 遍历指定的索引,拼接成字符串打印
        print(' '.join(str(row[idx]) for idx in fields_to_print))

调用示例:

  • 保持原行为:print_query_result(con, 'SELECT * from table')
  • 只打印第0和第2个字段:print_query_result(con, 'SELECT * from table', [0, 2])
  • 打印前4个字段:print_query_result(con, 'SELECT * from table', [0,1,2,3])

解决方案2:增加「打印所有字段」的快捷选项

如果你经常需要打印所有字段,可以再加一个print_all的布尔参数,开启后直接打印整行的所有内容,更方便:

def print_query_result(con, query, fields_to_print=None, print_all=False):
    con.execute(query)
    for row in con:
        if print_all:
            # 打印所有字段,用空格分隔
            print(' '.join(str(col) for col in row))
        else:
            # 使用默认或指定的字段索引
            if fields_to_print is None:
                fields_to_print = [0, 1, 3]
            print(' '.join(str(row[idx]) for idx in fields_to_print))

调用示例:

  • 打印所有字段:print_query_result(con, 'SELECT * from table', print_all=True)

额外优化:防止索引越界的健壮性处理

如果担心传入的索引超过了查询结果的字段数量(比如查询结果只有2个字段,但传了[0,1,3]),可以加个小过滤,只保留有效的索引,避免抛出IndexError:

def print_query_result(con, query, fields_to_print=None):
    if fields_to_print is None:
        fields_to_print = [0, 1, 3]
    con.execute(query)
    for row in con:
        # 过滤掉超出当前行字段数量的索引
        valid_indices = [idx for idx in fields_to_print if idx < len(row)]
        if not valid_indices:
            print("No valid fields to print for this row")
            continue
        print(' '.join(str(row[idx]) for idx in valid_indices))

这样你的函数就既灵活又健壮了,完全能满足动态调整打印字段数量的需求~

内容的提问来源于stack exchange,提问作者Karol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:11:23