简体   繁体   中英

Python, returning a tuple of tuples into locals inside a function

t = (('page',1),('count',25),('skip',0))

def get_arguments(t):
 page = 1
 count = 25
 skip = 0

Basically, what's best way to iterate over the tuple and set these arguments in my function like the example?

You can also use **kwargs :

t = (('page',1),('count',25),('skip',0))
arguments = dict(t)

def get_arguments(page, count, skip):
    #page = 1
    #count = 25
    #skip = 0

#call your function with
get_arguments(**arguments)

And don't name the variable as tuple .

tupleData = (('page',1),('count',25),('skip',0))

def get_arguments(tupleArg):
   page, count, skip = zip(*tupleArg)[1]
   print page, count, skip

get_arguments(tupleData)

Output

1 25 0
def get_arguments(page,count,skip):
     print page, count, skip

get_arguments(page=1, count=25, skip=0)

你可以这样做:

page, count, skip = [t[1] for t in tuple]
tupleData = (('page',1),('count',25),('skip',0))

class DottedDict(dict):
    def __init__(self, *a, **k):
        super(DottedDict, self).__init__(*a, **k)
        self.__dict__ = self

def get_arguments(tupleArg):
   d = DottedDict(tupleArg)
   print d.page, d.count, d.skip

get_arguments(tupleData)

In principle, a normal dict would work as well if you do d['page'] etc. instead, but the dotted access is even shorter.

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