Skip to main content
 首页 » 编程设计

python之如何使用python将数据显示为数组格式

2025年05月04日15youxin

def index(request): 
    conn = MySQLdb.connect(host="localhost", user="user", passwd="pwd", db="highchart_with_django") 
    cursor = conn.cursor() 
    cursor.execute("SELECT categories,tokyo,london,new_york,berlin FROM basic_line_chart") 
    row = cursor.fetchone() 
    while row is not None: 
       print row 
       row = cursor.fetchone() 
    return render(request, "linechart.html") 

输出如下:

('Sep', Decimal('7.00'), Decimal('3.90'), Decimal('-0.20'), Decimal('-0.90')) 
('Oct', Decimal('6.90'), Decimal('4.20'), Decimal('0.80'), Decimal('0.60')) 

期望输出:

 ["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"] 

我怎样才能做到这一点。请帮我解决这个问题。

请您参考如下方法:

根据此链接http://mysql-python.sourceforge.net/MySQLdb.html fetchone() 返回一个元组。

要将其转换为列表,只需将其强制转换即可。

row = list(cursor.fetchone()) 

然后您可以迭代该列表,以您正在寻找的正确格式获取它们。