简体   繁体   中英

How to “unpack” this tuple

I have a Python variable (database record) that prints as follows:

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

What is the best way to print these two values? I want to do something like this:

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

The left side unpacking needs to match the structure of the right side. So this will work:

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

You have a single-item tuple whose contents is a two-item tuple

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'

see how to unpack argument lists , and format examples

or use the old %-formatting operator :

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

If you're only expecting a single row as a result, then just use .fetchone() instead and then you don't have to worry unpacking it, eg:

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

Or, if you have more, then loop over the cursor:

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

Another option, for varitey:

value = ((79321L, Decimal('11.56125119')),)
a, b = list(value)[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM