current position:Home>Python * * packaging and unpacking details

Python * * packaging and unpacking details

2022-01-31 21:52:15 LolitaAnn

Participate in 11 The fourth of the yuegengwen challenge 18 God , Check out the activity details :2021 One last more challenge

The English in it comes from python Developer's Guide to the official website PEP 448 -- Additional Unpacking Generalizations | Python.org

This paper mainly introduces * and ** This is described in detail .

Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays.

Unpacking can be applied to tuples 、 list 、 aggregate 、 Dictionaries .

  • *args:argument For list 、 Tuples 、 aggregate
  • **kwargs:kwargument For dictionaries

First, let's review range, And with range Generate tuples 、 Lists and collections .

li = list(range(7))
print(li)
tu = tuple(range(7))
print(tu)
se = set(range(7))
print(se)
 Copy code 
[0, 1, 2, 3, 4, 5, 6]
(0, 1, 2, 3, 4, 5, 6)
{0, 1, 2, 3, 4, 5, 6}
 Copy code 

Available locations

* and ** It can be used for unpacking anywhere .

Specifically, in function calls, in comprehensions and generator expressions, and in displays.

  • function calls: Function call
  • comprehensions and generator expressions: Generator derivation
  • displays: Show ( My understanding is to output directly ?)

display

The so-called display, I think, is direct output ,( It can't always be direct output ).

li = list(range(7))
tu = tuple(range(7))
se = set(range(7))

print(*li,*tu,*se)

 Copy code 
0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6
 Copy code 

Above is * Complete the list directly 、 Unpacking tuples and sets .

But it doesn't work ** Unpack the dictionary ,print(**{"name":"sian","name":25}) Will report a mistake SyntaxError: invalid syntax.

Although it cannot be used for direct output , But you can slice .

dic = {"name":"sian","name2":"sian"}
a = {'a':0,**dic,'c':1}

print(a)
 Copy code 
{'a':0,"name":"sian","name2":"sian",'c':1}
 Copy code 

** You can slice it , that * It's fine too :

li = [1,2,3]
a = [1,*li,0]

print(a)

 Copy code 
[1, 1, 2, 3, 0]
 Copy code 

Comprehensions and generator expressions

The generator derivation is :

print(i for i in range(7))
 Copy code 
<generator object <genexpr> at 0x000002502D43A510>
 Copy code 

The output tells you that this is a generator object .

You can create lists and collections with generator objects , But you can't create tuples directly .

li = [i for i in range(7)]
se = {i for i in range(7)}
print(li,se)
 Copy code 
[0, 1, 2, 3, 4, 5, 6] {0, 1, 2, 3, 4, 5, 6}
 Copy code 

use * The unpacker object is :

print(*[i for i in range(7)])
 Copy code 
0 1 2 3 4 5 6
 Copy code 

Directly save the variable name :clap:.

Function call

It's common for function calls .

def function(num,*args):
    print(num)
    print(args)
    print(*args)
    
function(1,2,3,4,5,6,7)
function('a',1,2,3,'b')
 Copy code 
1
(2, 3, 4, 5, 6, 7)
2 3 4 5 6 7
a
(1, 2, 3, 'b')
1 2 3 b
 Copy code 

*args It is used to receive parameters of any length and package them and store them in tuples .

But the location is not flexible enough , It will receive from *args All parameters from the start position to the end .

  • such as def function(first,*args,last):,last Will not receive parameters , Report errors function() missing 1 required keyword-only argument: 'last'

    But you can manually specify parameters to solve this problem . For example, forcibly give last A value .

    def function(first,*args,last="c"):
        print("first:",first)
        print(args)
        print("last:",last)
    
    function(1,2,3,4,5,6,7)
     Copy code 
    first: 1
    (2, 3, 4, 5, 6, 7)
    last: c
     Copy code 
  • *args Previous parameters cannot be specified manually .

    def function(first='a',*args):
        print("first:",first)
        print(args)
        
    function(1,2,3,4,5,6,7)
     Copy code 
    first: 1
    (2, 3, 4, 5, 6, 7)
     Copy code 

Look again. ** Receive parameters and package them as dictionaries .

def function(first='a',**kwargs):
    print("first:",first)
    print(kwargs)
    
function(1,name = "Sian", age = 25,b=2)
 Copy code 
first: 1
{'name': 'Sian', 'age': 25, 'b': 2}
 Copy code 

The position of the parameter list is a little different from * equally , Also, there can be no parameters after . Will report a mistake SyntaxError: invalid syntax. But the previous parameters can be specified .

copyright notice
author[LolitaAnn],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312152138150.html

Random recommended