Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack only some arguments from zip, not all?

Tags:

python

My sql query:

 select id,value,zvalue from axis

gives me result like this:

   ans=(1,23,34)(12,34,35)(31,67,45)(231,3412,234)

now if i want all these 3 variables as 3 different lists

id,value,zvalue=zip(*ans)

it will give me 3 separate lists. but if i only want id and value as separate lists.It will give me TOO MANY VALUES TO UNPACK ERROR.

id,value =zip(*ans)

is there any way where i can create any number of lists from sql query.because if there are 10 parameters in the query , i have to use all the parameters while using ZIP??? please help

like image 380
saun jean Avatar asked Jan 28 '12 22:01

saun jean


1 Answers

The number of arguments must match, this is a rule in Python 2. For Python 3, you can use * to capture into a list.

The common pythonic (2.x) workaround is to use _ to denote variables you won't use, i.e.:

id,value,_ = zip(*ans) # only works for exactly three values

As DSM commented, for Python 3, you can use * to grab "remaining" args as a list:

id, value, *_ = zip(*ans) # _ will be a list of zero or more args

Or, simplest, just slice the return from zip:

id,value = zip(*ans)[:2] # ignore all but first two values  
like image 199
Macke Avatar answered Sep 19 '22 16:09

Macke