Python—从存储在变量中的SQL输出中读取特定列

Python—从存储在变量中的SQL输出中读取特定列,python,sql,python-3.x,amazon-redshift,Python,Sql,Python 3.x,Amazon Redshift,我这里有一个基本问题。我正在提取一个SQL输出,如下所示: cur = connection.cursor() cur.execute("""select store_name,count(*) from stores group by store_name""") data = cur.fetchall() Store_1,23 Store_2,13 Store_3,43 Store_4,2 上述SQL的输出如下: cur = connection.cursor() cur.execut

我这里有一个基本问题。我正在提取一个SQL输出,如下所示:

cur = connection.cursor()
cur.execute("""select store_name,count(*) from stores group by store_name""")
data = cur.fetchall() 
Store_1,23
Store_2,13
Store_3,43
Store_4,2
上述SQL的输出如下:

cur = connection.cursor()
cur.execute("""select store_name,count(*) from stores group by store_name""")
data = cur.fetchall() 
Store_1,23
Store_2,13
Store_3,43
Store_4,2
我正在尝试读取上述输出中的第1列store_名称

预期产出:

Store_1
Store_2
Store_3
Store_4

谁能给我一个建议,我该怎么做。谢谢..

如果我正确理解了您的问题,我想只要更正SQL就可以得到所需的结果。获取不同的存储名称

select distinct store_name from stores
编辑

对评论的答复:

请尝试以下操作:

from operator import itemgetter
data = cur.fetchall() 
list(map(itemgetter(0), data)) # your answer

在代码中,只需附加以下行:

for rows in data:
    print(rows[0])
希望这有帮助

顺便说一句:我不在电脑上,也没有交叉检查解决方案。

哈佛的CS50网站有以下内容,我认为在最后3行中对您有所帮助

  import os    
  from sqlalchemy import create_engine
  from sqlalchemy.orm import scoped_session, sessionmaker

  engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database
                                                    # DATABASE_URL is an environment variable that indicates where the database lives
  db = scoped_session(sessionmaker(bind=engine))    # create a 'scoped session' that ensures different users' interactions with the
                                                    # database are kept separate

  flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall() # execute this SQL command and return all of the results
  for flight in flights
      print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.") # for every flight, print out the flight info
因此,在你的情况下,我认为:

results = db.execute( <PUT YOUR SQL QUERY HERE> )
for row in results:
    print(row.store_name)

我获取了一个当前存储在变量“data”中的输出。这当前有两列。我试图过滤掉第一列store_名称,并从数据中返回该名称。