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

嵌套for循环解析psycopg2返回嵌套列表的问题求助

问题描述

通过psycopg2执行PostgreSQL查询后得到嵌套列表,每个子列表包含企业名称、股票代码、行业信息。尝试用嵌套for循环提取每行的第1个(企业名称)和第3个(行业)元素并打印,但循环控制逻辑错误,无法得到预期输出。

示例数据:企业名称为American Airlines,股票代码为AAL,行业为Airlines。

PostgreSQL查询代码

# psycopg2 query to pull company name and industry based on stock ticker
cur.execute('SELECT company,stockTicker,industry FROM stockNames WHERE stockTicker = %s',(stockChoice,))
records=cur.fetchall()

当前嵌套循环代码

for i in records:
     for j in i:
          count=0
          if count==0:
               print('\n' 'Company Name: ',j)
               print('Stock Ticker: ',stockChoice)
               continue
          if count==1:
               continue
          if count==2:               
               print('Industry: ',list,j)
               print('Stock Price: ',stockPrice.text)
               continue
          count+=1

当前错误输出

Company Name:  American Airlines
Stock Ticker:  AAL

Company Name:  AAL
Stock Ticker:  AAL

Company Name:  Airlines
Stock Ticker:  AAL

期望输出

Company Name: American Airlines
Stock Ticker: AAL
Industry: Airlines

修正方案

问题根源

  1. count变量在每次遍历子元素j时都被重置为0,导致每次循环都触发count==0的条件;
  2. count+=1语句在continue之后,永远不会被执行,count值始终不变;
  3. 完全没必要用嵌套循环——records中的每个元素是元组,直接通过索引访问对应字段更高效。

方案1:简化代码(推荐)

直接利用元组索引提取目标字段,无需嵌套循环:

for record in records:
    company_name = record[0]
    industry = record[2]
    print(f"Company Name: {company_name}")
    print(f"Stock Ticker: {stockChoice}")
    print(f"Industry: {industry}")
    # 若需打印股价可取消注释
    # print(f"Stock Price: {stockPrice.text}")

方案2:修复原循环逻辑

如果一定要保留嵌套循环结构,调整count的位置并修正控制流:

for i in records:
    count = 0  # 将count移至内层循环外,处理每行时重置计数
    for j in i:
        if count == 0:
            print('Company Name: ', j)
            print('Stock Ticker: ', stockChoice)
        elif count == 1:
            pass  # 跳过股票代码字段
        elif count == 2:
            print('Industry: ', j)
            # print('Stock Price: ', stockPrice.text)
        count += 1  # 每次循环后计数自增

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:20:14