如何“解包”这个tup

2024-04-25 23:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python变量(数据库记录),打印如下:

((79321L, Decimal('11.56125119')),)

打印这两个值的最佳方法是什么?我想这样做:

print("Count: {}, Result: {}".format(cur.fetchall()))

Tags: 方法数据库formatcount记录resultdecimalprint
3条回答

如果您只希望得到一行结果,那么只需使用.fetchone(),就不必担心解包了,例如:

print('Count: {} Result: {}'.format(*cur.fetchone()))

或者,如果有更多,则在光标上循环:

for row in cur:
    print('Count: {} Result: {}'.format(*row))

左侧开箱需要与右侧结构相匹配。所以这会起作用:

((x, y),) = ((79321L, Decimal('11.56125119')),)

您有一个单项元组,其内容是一个双项元组

In [10]: a=((79321L, Decimal('11.56125119')),)
#a[0] is a tuple, use "*" to unpack a tuple when passing it as parameters:
In [11]: "Count: {}, Result: {}".format(*a[0])
Out[11]: 'Count: 79321, Result: 11.56125119'

参见how to unpack argument lists,和format examples

或者使用old %-formatting operator

In [13]: "Count: %s, Result: %s"%a[0]
Out[13]: 'Count: 79321, Result: 11.56125119'

相关问题 更多 >