Some tips for python (exchange two numbers)

Packet unpacking tuples
  • Packet tuple
    packets that some tuples into a tuple count packages.
  • Unpack tuples
    to a tuple all broken, assigned to specific variables. Note that the number of elements and the number of tuple elements must be consistent with, or be wrong
  • python swap two numbers is to use a packet unpacking knowledge
my_tuple = 1,2,3,4
print(type(my_tuple)) # <class 'tuple'>
a,b,c,d = my_tuple # a = 1, b = 2,c = 3,d = 4

numOne = 10 
numTwo = 20
numTwo,numOne = numOne,numTwo
print(numOne,numTwo) # 20 10
Keyword parameters and location parameters

Keyword arguments parameters like position on the back, it seems, do not spray, long knowledge, and forgotten.

  • Keyword parameters
    assigned to the same parameter names based on keywords
def fun(a,b,c):
    print('a =',a,'b =',b,'c =',c)# a = 1 b = 2 c = 3
fun(1,c = 2,b = 3)

  • Position parameter
    according to the position assigned to the arguments of the particular parameter
def fun(a,b,c):
    print('a =',a,'b =',b,'c =',c) # a = 1 b = 3 c = 2
fun(1,2,3)
And unpack the packet parameters
  • Packaged into variable length parameter tuple
def fun(*arr):
    print(type(arr)) # <class 'tuple'>
    for i in range(len(arr)):
        print(arr[i],' ',end='') # 1  2  3  
fun(1,2,3)
  • Tuple parameter passing unpacks a single element, the number of note to be consistent
def fun(a,b,c):
    print(a,b,c) # 1 2 3
fun(*(1,2,3))
  • Variable = value of variable length, packaged Dictionary
def fun(**mydict):
    for key in mydict:
        print(key,':',mydict[key],end=' ') # a : 1 b : 2 c : 3 
fun(a=1,b=2,c=3)
  • Dictionary parameter passing, broken down into individual variables, note the name and number to be consistent
def fun(a,b,c):
    print('a:',a,'b:',b,'c:',c) # a: 1 b: 2 c: 3
mydict = {'a':1,'b':2,'c':3}
fun(**mydict)

Guess you like

Origin blog.csdn.net/jdq8576/article/details/94750296