简体   繁体   中英

Unpacking tuple in Python 2.7

Actually working on a project where the homemade local DB api return all the result of SQL requests in tuples.

Like that :

result = ( (result1.1, result1.2... ), (result2.1, .... ) .... )

The problem is : when they unpack the tuple, we get many, many... ( many ) ValueErrors, because they do it like that :

( (result1.1, result1.2... ), (result2.1, .... ) .... ) = result

Which leads to these errors :

a = (1, 2)
(b,) = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

(b, c, d) = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack    

What would be the best way to avoid these errors ( mostly due to the fact that we systematically add columns in the requests ) ?

I'm not really familiar with the *args **kwargs syntax, but I suppose we could use it?

Should we use another data structure (list, dictionary, ...)?

Edit :

def myFunction():

    sql = "SELECT a, b FROM myTable WHERE ...."
    myTuple = db.fetch(sql)        
    # I.E. : myTuple = ((a1, b1), (a2, b2))
    return myTuple

myTuple = myFunction()
for t in myTuple:
    (a, b) = t        

My problem is : When I need to fetch column c in my request, how do I handle it when I unpack it?

  1. Use Better Data Structure

You should consider to use proper data like list of Classes / Objects then you don't need to "unpack" them like this

  1. Play with data Part 1
for subValue in a:
    my = GetValueOrDefault(subValue, 0)
    killer = GetValueOrDefault(subValue, 1)
    data = GetValueOrDefault(subValue, 2)

def GetValueOrDefault(value, index, default=None):
    returnValue = default

    try:
        returnValue = value[index]
    except:
        pass

    return returnValue
  1. Play with data Part 2
newDict = [{index: value for index, value in enumerate(item)} for item in result]

python is flexible, use what fits to your need

For Python3: use asterisk syntax

result = ((1,2), (3,4), (5,6))
a, *_ = result
# a == (1,2)
# _ == [(3,4),(5,6)]

For Python2: use slices

result = ((1,2), (3,4), (5,6))
a, b = result[:2]
# a == (1,2)
# b == (3,4)

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