Python tuple unpacking and naming notes 004 tuples

Python tuple unpacking and naming notes 004 tuples

The following is a personal note I study "Python smooth" after, and now out for all to share, I hope to help you Python learners.

First published in: micro-channel public number: technology old Dingo, ID: TechDing, so stay tuned.

Data in this chapter knowledge:

  1. Unpacking tuples is to assign each one to one tuple element according to the position inside the different variables to be applied to the variable assignment, the function parameter assignment, acquires a position value of a specific element of the tuple and other occasions.

  2. namedtuple: storing a sequence of objects, the element values ​​can not be changed, as can be accessed through the same names dict, by _asdict () is converted to dict, which acts only class attribute does method.

1. tuple unpacking

Similarly tuple of tuples and lists in the list Python, except that the elements of the tuple can not be changed, it is often referred to as immutable list () in the form indicated by parentheses, tuple, and the list enclosed in brackets [ ] representation.

Unpacking tuples is to assign each one to one of the elements according to the position inside tuple to different variables, such as:

tupleA=(10,20.5)
first,second=tupleA # 对二元素元组拆包
print(first) # 10
print(second) # 20.5

a,b,c,d=('A',20.15,2019,'10:15:14') # 多元素元组的拆包
print(a) # A
print(b) # 20.15
print(c) # 2019
print(d) # 10:15:14

If the above applies to unpacking simple assignment, but added that no novelty. In fact, unpacking is often used for parameter assignment to the function, such as:

def func1(a,b):
    print('a: ',a,'b: ',b)
tupleA=(10,20.5)
func1(*tupleA) # 拆包后作为函数的参数,a:  10 b:  20.5

Another unpacking scenario is that certain functions return a tuple, and unpacking we need to be, such as:

def func2(x):
    return (x,x*2,x*x)
data1,data2,data3=func2(3)
print(data1) # 3
print(data2) # 6
print(data3) # 9

When unpacking, and some elements are not what we need, then use placeholders instead, which uses _ represents a placeholder, and * represents more placeholders

data1,_,data3=func2(3) # 用_代表一个变量
print(data1) # 3
data1,*rest=func2(3)
print(data1) # 3
print(rest) # [6,9]

Nested tuple, the tuple by definition is contained in tuple, its ordinary and unpacking unpacking tuple similar.

areas=[('hubei','wuhan',1200,(150,260)),
       ('hunan','changsha',3600,(100,200)),
       ('shandong','jinan',800,(260,180))]
for province,city,data1,(data2,data3) in areas:
    print('P:{}, C:{}, data2:{},data3:{}'.format(province,city,data2,data3))

2. Name the tuple

Named tuples (namedtuple) similar to the tuple, the sequence can be used to store objects, but it is more powerful than the tuple, in addition to the continuation of tuple elements can not change the value of this property, there are features of its own, such as can be like dict access element value by name, but also () dict converted to type by _asdict.

Named tuples can be constructed tuple and a class name with a field name, and tuples memory it consumes is the same.

In object-oriented thinking, if we need to build a simple class, just to store a few simple properties, but no specific method, we can write:

class PersonCls:# 定义一个类,只有属性,没有具体的方法,用于存储某些属性值
    def __init__(self,name,age,score):
        self.name=name
        self.age=age
        self.score=score
    def __repr__(self):
        return 'PersonCls(name={},age={},score={})'.format(self.name,self.age,self.score)

PC1=PersonCls('Jack',20,85)
PC2=PersonCls('Rose',18,92)
print(PC1) # PersonCls(name=Jack,age=20,score=85)
print(PC2) # PersonCls(name=Rose,age=18,score=92)
print(PC1.age) # 20
print(PC2.score) # 92

Such wording is feasible, but not Python style, this situation is entirely possible to do namedtuple, for example, is written in python inside:

from collections import namedtuple
Person=namedtuple('Person',['name', 'age', 'score']) # 构造一个namedtuple类

P1=Person('Jack',20,85) # 构建具体的实例,其赋值顺序要一一对应
P2=Person(age=18,name='Rose',score=92) # 如果指定变量名,顺序不用一一对应
print(P1) # Person(name='Jack', age=20, score=85)
print(P2) # Person(name='Rose', age=18, score=92)
print(P1.age) # 可以像dict一样通过属性名进行访问
print(P2.score) # 92

The above Person=namedtuple('Person',['name', 'age', 'score'])is equivalent to the Person class construct a property not only of the method, which is a property: 'name', 'age' , 'score', code simpler and more Python taste. In memory, it will be less than the definition of a class, you do not need because the __dict__property to store instance.

Named tuples addition to the properties inherited from the tuple, there are proprietary properties, the most commonly used _fields, _make(), _asdict(). as follows:

# namedtuple专有属性:
from collections import namedtuple
Person=namedtuple('Person',['name', 'age', 'score'])
print(Person._fields) # ('name', 'age', 'score')
# _fields属性是一个包含这个类所有属性名称的tuple

person1=('zhangsan',25,59)
p1=Person._make(person1) # _make()接受一个可迭代对象生成一个实例
print(p1) # Person(name='zhangsan', age=25, score=59)

print(p1._asdict()) # OrderedDict([('name', 'zhangsan'), ('age', 25), ('score', 59)])
# _asdict()将实例的属性和值以OrderedDict的方式展示出来。

First published in: micro-channel public number: technology old Dingo, ID: TechDing, so stay tuned.

In this paper all of the code have been uploaded to my GitHub , welcome to download

References:

  1. "Fluent Python", Luciano Ramalho (Author) Andorra, Wu Ke (translator).

Guess you like

Origin www.cnblogs.com/RayDean/p/10987950.html