首页 > 解决方案 > 如何在python中拆分元组并获取具有列名的数据

问题描述

import cv2
import NumPy as np
import face_recognition
import os
from DateTime import DateTime
from SQL import mydb

mycursor = mydb.cursor()
mycursor.execute("SELECT name, age,imageURL,gender FROM staff")
myresult = mycursor.fetchone()

name = myresult[0]
age = myresult[1]
imgs = myresult[2]
gender = myresult[3]

需要拆分来自 mySQl 的元组

当前结果:

[(2, 'Joe', '30', 'Male', 'images/Joe.jpg'), (3, 'Doe', '28', 'Male', 'images/Doe.jpg')]

必需的:

(2, 'Joe', '30', 'Male', 'images/Joe.jpg')
(3, 'Doe', '28', 'Male', 'images/Doe.jpg')

之后需要将其放入列中

ID Name Age Gender imageURL 
2  Joe  30  Male   images/Joe.jpg
3  Doe  28  Male   images/Doe.jpg

应用贾斯汀的建议后:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database = "face_db"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM staff")

myresult = mycursor.fetchall()

for (ID, Name, Age, Gender, imageURL) in myresult:
    print(ID,Name,Age,Gender,imageURL)

从这里我有单独的 ID、姓名、年龄和性别,但缺少列名

标签: pythonmysqlsplittuples

解决方案


这称为元组解包。

print("ID", "Name", "Age", "Gender", "imageURL") # print your headers
for (ID, Name, Age, Gender, imageURL) in myresult:
    print(ID, Name, Age, Gender, imageURL) # print the values


推荐阅读