Python:显示游标中元组的第一个元素
Python: display first element of tuple in cursor
我有以下代码:
conn = mysql.connector.connect(database='test', user='me', password='pwd')
cursor = conn.cursor()
query = ( "select id from T where project = 10" )
cursor.execute(query)
result = cursor.fetchall()
结果显示为:
[(Decimal('476749'),), (Decimal('478045'),), (Decimal('479713'),)]
是否可以显示为:[476749, 478045, 479713]
您可以使用 zip
函数获取第一项,并使用 map
将小数转换为整数:
>>> import decimal
>>> map(int,zip(*[(decimal.Decimal('476749'),), (decimal.Decimal('478045'),), (decimal.Decimal('479713'),)])[0])
[476749, 478045, 479713]
在您的代码中:
result = map(int,zip(*cursor.fetchall()))
既然 python 优雅得多,为什么还要使用 zip/map?
[int(i[0]) for i in cursor.fetchall()]
我有以下代码:
conn = mysql.connector.connect(database='test', user='me', password='pwd')
cursor = conn.cursor()
query = ( "select id from T where project = 10" )
cursor.execute(query)
result = cursor.fetchall()
结果显示为:
[(Decimal('476749'),), (Decimal('478045'),), (Decimal('479713'),)]
是否可以显示为:[476749, 478045, 479713]
您可以使用 zip
函数获取第一项,并使用 map
将小数转换为整数:
>>> import decimal
>>> map(int,zip(*[(decimal.Decimal('476749'),), (decimal.Decimal('478045'),), (decimal.Decimal('479713'),)])[0])
[476749, 478045, 479713]
在您的代码中:
result = map(int,zip(*cursor.fetchall()))
既然 python 优雅得多,为什么还要使用 zip/map?
[int(i[0]) for i in cursor.fetchall()]