尝试使用嵌套的for循环来正确解析嵌套的列表项



我有一个嵌套列表(来自psycopg2 psql查询),其中包含公司名称、股票报价机和行业列表。我使用随后的嵌套for循环尝试从随后的print语句中的嵌套列表行中提取第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循环如下:

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

任何帮助在这是感激得到控制流正确的我正在尝试做的。

不要使用嵌套循环。只需将每一行解压为变量

for company, ticker, industry in records:
print(f'Company name: {company}nStock ticker: {ticker}nIndustry: {industry}n')

如果你只获取一只股票的信息,就根本不需要循环。

cur.execute('SELECT company,stockTicker,industry FROM stockNames WHERE stockTicker = %s',(stockChoice,))
row = cur.fetchone()
if row:
company, ticker, industry = row
print(f'Company name: {company}nStock ticker: {ticker}nIndustry: {industry}n')

最新更新