創建只有一個元素的元組


定義元組

>>> a = ()  #定義元組a
>>> b = (1, 2, 3, 4, 5)  #定義元組b
>>> c = ('Hi', 'python', '!')  #定義元組c
>>> d = ('Tom', 20, 'Jack', 19)  #定義元組d
>>> print(a,b,c,d)  #打印元組a,b,c,d
() (1, 2, 3, 4, 5) ('Hi', 'python', '!') ('Tom', 20, 'Jack', 19)

上面例子中的a是一個空的元組,與定義空列表差不多,直接使用a = ()就能將一個空的元組賦值給a。
需要注意的是,由於元組使用的是小括號,在數學中,有時候需要使用小括號來指定計算順序,例如(2+3)/5,這時候優先計算2+3,然后再除以5。在python中,小括號同樣指定計算順序,在定義只有一個元素的元組時就會產生歧義。因此,使用以下方法定義一個只含有一個元素的元組。

>>> a = (1,)  #定義元組a
>>> b = ('Tom',)  #定義元組b
>>> c = (1)  #定義c
>>> d = ('Tom')  #定義d
>>> print(type(a))  #打印a的類型
<class 'tuple'>
>>> print(type(b))  #打印b的類型
<class 'tuple'>
>>> print(type(c))  #打印c的類型
<class 'int'>
>>> print(type(d))  #打印d的類型
<class 'str'>

namedtuple

Python的Collections模塊提供了不少好用的數據容器類型,其中一個精品當屬namedtuple。

namedtuple能夠用來創建類似於元祖的數據類型,除了能夠用索引來訪問數據,能夠迭代,更能夠方便的通過屬性名來訪問數據。


源碼:
def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
    """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM