Featured post
python - better way of handling nested list -
my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]] item in my_list: var1,var2,var3,var4,var5,var6 = none if len(item) ==1: var1 = item[0] if len(item) == 2: var1 = item[0] var2 = item[1] if len(item) == 3: var1 = item[0] var2 = item[1] var3 = item[2] if len(item) == 4: var1 = item[0] var2 = item[1] var3 = item[2] var4 = item[3] fun(var1,var2,var3,var4,var5,var6)
i have function
def fun(var1, var2 = none, var3 = none, var4 = none, var5=none, var6= none)
depending upon values in inner list. passing function. hope made clear.
thanks
see calls , function definitions in python documentation, specifically:
if syntax *expression appears in function call, expression must evaluate sequence. elements sequence treated if additional positional arguments....
if syntax **expression appears in function call, expression must evaluate mapping, contents of treated additional keyword arguments....
...a function call assigns values parameters mentioned in parameter list, either position arguments, keyword arguments, or default values. if form “*identifier” present, initialized tuple receiving excess positional parameters, defaulting empty tuple. if form “**identifier” present, initialized new dictionary receiving excess keyword arguments, defaulting new empty dictionary.
example 1
you need following, since arguments simple integers:
my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]] def func(*var): arg in var: print arg, print args in my_list: func(*args)
output 1
1 2 3 4 5 6 1 3 4 34 56 56 56
example 2
the next example shows can fill in number of arguments function defaults:
my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]] def func(var1=none,var2=none,var3=none,var4=none,var5=none,var6=none): print var1,var2,var3,var4,var5,var6 args in my_list: func(*args)
output 2
1 2 3 4 5 6 1 3 4 none none none 34 56 56 56 none none
example 3
you can fill them in out-of-order **
syntax:
my_list = [dict(var1=1,var5=5,var6=6),dict(var2=2,var4=4)] def func(var1=none,var2=none,var3=none,var4=none,var5=none,var6=none): print var1,var2,var3,var4,var5,var6 args in my_list: func(**args)
output 3
1 none none none 5 6 none 2 none 4 none none
- Get link
- X
- Other Apps
Comments
Post a Comment