python 内置数据操作 --- 列表list、元组tuple、字典dict、集合

在python中,有一类数据结构,通过包含的方式存储数据的,称之为容器(container)。其中,列表、元组、字符串都属于序列(有序性),字典属于映射(通过键映射值),而集合(set)是一种无序、自动去重的数据结构。本篇总结了列表、元组、字典和集合,字符串方法请参照上一篇

 

一、列表

python作为一门弱类型语言,创建数据的方式较为简单。列表创建方式如下:

list() -> new empty list
list(iterable) -> new list initialized from iterable's items

列表类的内置方法:

  

    def append(self, p_object): 
        """ L.append(object) -> None -- append object to end """
        pass
    
    直接将p_object参数添加到列表末尾,此操作直接在原列表上完成,不返回任何值。



        def clear(self):
        """ L.clear() -> None -- remove all items from L """
        pass

    情况列表内所有元素,此操作直接在原列表上完成,不返回任何值。



    def copy(self): 
        """ L.copy() -> list -- a shallow copy of L """
        return []

    返回一个原列表的浅拷贝列表。



    def count(self, value): 
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

     返回value参数值在列表中存在的个数。



    def extend(self, iterable):
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

     将可迭代对象参数iterable拓展到当前列表中。当iterable为字符串时,将字符串的每一个字符作为元素扩展到列表中;当iterable为字典时,则将字典的键作为元素扩展到列表中。不返回任何值。



    def index(self, value, start=None, stop=None):
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

     在列表[start:end]切片中寻找value值元素第一次出现的索引,并返回该索引值。默认start、end为None时,则在整个列表中查询,当未找到value值时,会抛出ValueError的异常。



    def insert(self, index, p_object): 
        """ L.insert(index, object) -- insert object before index """
        pass

     在index索引位置之前插入p_object,操作完成后L[index] == p_object。



    def pop(self, index=None): 
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

     删除并返回索引为index的元素值,默认删除最后一个。当列表为空或者index值超出列表索引范围时,将会抛出IndexError异常。



    def remove(self, value): 
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

     删除列表中第一个出现的值为value的元素,当value不存在于列表中时,抛出VauleError异常。



    def reverse(self): 
        """ L.reverse() -- reverse *IN PLACE* """
        pass

     将整个列表元素反转,不返回值



    def sort(self, key=None, reverse=False): 
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass
    
     对所有元素进行稳定排序,不返回值。

二、元组

元组(tuple)的创建方法如下:

tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
    
If the argument is a tuple, the return value is the same object.

 

由于元组创建后不能进行修改的特性,故其内置方法较少(不能增删改,只能查):

    def count(self, value):
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

     返回value值在元组中出现的次数。



    def index(self, value, start=None, stop=None):
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

     返回T[start:end]中,value第一次出现的索引值,如果value不存在,则抛出VauleError异常。

 

三、字典

字典(dict)的创建如下:

dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
     (key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
     d = {}
     for k, v in iterable:
         d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list.  For example:  dict(one=1,two=2)

字典内置方法:

    def clear(self): 
        """ D.clear() -> None.  Remove all items from D. """
        pass

    清空字典,不返回值。
    


    def copy(self): 
        """ D.copy() -> a shallow copy of D """
        pass

    对字典进行浅拷贝,并返回拷贝字典



    @staticmethod 
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

    返回一个新字典,这个字典是以第一个参数(可迭代对象)的循环返回值为键,第二个参数为值的。也就是返回字典的所有键对应的值都一样。



    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass
    
     返回字典中key为k的值,如果不存在,则返回d。默认d为None。



    def items(self): 
        """ D.items() -> a set-like object providing a view on D's items """
        pass

     返回一个dict_items的可迭代、类集合对象,其内部组成为:[(key1, value1),(key2, value2),.....],每一个元组元素为字典的一个键值对元素。一般通过这种方法遍历字典,来分别拿到字典的键和值。例:
     for key, value in dict.items():
          print(key, value)



    def keys(self): 
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

     返回一个dict_keys的可迭代、类集合对象,其内部形式为:[key1,key2,key3,....],即将字典的键都放在一个类似集合的容器中。可以用来判断某个key是否存在于字典中:
    if key in dict.keys():
        print(key)



    def pop(self, k, d=None): 
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    删除字典中键为k的元素,并返回k键对应的值。如果键为k的元素不存在时,给d传参,则返回d;d为None则,引发KeyError异常。



    def popitem(self): 
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
        """
        pass

    随机删除一个元素,并把删除元素的键和值放在一个元组里返回:(key, value)。



    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    先在字典里查找是否存在键为k的元素,如果存在则返回k键对应的值,如果不存在则为字典添加一个键为k、值为d的元素(d默认为None),并返回d的值。



    def update(self, E=None, **F): 
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    从E和F两个可迭代对象参数中向字典中添加元素。如果E参数有keys()方法,则执行:
    for k in E:
        D[k] = E[k]
  如果没有keys()方法,则执行:
    for k, v in E: 
        D[k] = v
  不管哪种方法,都是紧随:
    for k in F:  
        D[k] = F[k]


    def values(self): 
        """ D.values() -> an object providing a view on D's values """
        pass

    返回一个dict_values对象,其内部结构为[value1,value2, value3,...],可以用来收集字典的值。

 四、集合

集合(set)的创建方式如下:

set() -> new empty set object
set(iterable) -> new set object
    
Build an unordered collection of unique elements.

集合内置方法:

    def add(self, *args, **kwargs): 
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass

    给集合添加一个元素,当元素已存在时,集合不变。



    def clear(self, *args, **kwargs): 
        """ Remove all elements from this set. """
        pass

    清空集合,删除所有元素。



    def copy(self, *args, **kwargs):
        """ Return a shallow copy of a set. """
        pass

    返回一个集合的浅拷贝对象。



    def difference(self, *args, **kwargs):
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)
        """
        pass

    返回当前集合与参数集合(至少一个,为空时返回原集合)的差集(差集即指元素在当前集合中但又不包含于其他集合参数中)。



    def difference_update(self, *args, **kwargs): 
        """ Remove all elements of another set from this set. """
        pass

    从原集合中删除参数集合所包含的所有元素(参数集合可以多个),不返回值。



    def discard(self, *args, **kwargs): 
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.
        """
        pass
    
    删除集合中的一个元素。当集合不包含该元素时,不做操作。不返回值



    def intersection(self, *args, **kwargs): 
        """
        Return the intersection of two sets as a new set.
        
        (i.e. all elements that are in both sets.)
        """
        pass

    返回两个集合的交集(交集的元素同时存在两个集合中)。



    def intersection_update(self, *args, **kwargs):
        """ Update a set with the intersection of itself and another. """
        pass

    将原集合的元素更改为原集合与参数集合的交集。



    def isdisjoint(self, *args, **kwargs): 
        """ Return True if two sets have a null intersection. """
        pass

    原集合与参数集合没有交集时,返回True,否则False。



    def issubset(self, *args, **kwargs): 
        """ Report whether another set contains this set. """
        pass

    判断原集合是否为参数集合的子集。



    def issuperset(self, *args, **kwargs): 
        """ Report whether this set contains another set. """
        pass

    判断参数集合是否为原集合的子集。



    def pop(self, *args, **kwargs):
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

    任意删除一个元素,并返回该元素。当集合为空时,抛出KeyError异常。



    def remove(self, *args, **kwargs):
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.
        """
        pass

    删除集合中指定元素,如果集合不包含该元素,则抛出KeyError异常。



    def symmetric_difference(self, *args, **kwargs):
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

    返回两个集合的并集(所有元素只能包含于两个集合中的一个)。



    def symmetric_difference_update(self, *args, **kwargs): 
        """ Update a set with the symmetric difference of itself and another. """
        pass

    将原集合的元素更改为原集合与参数集合的并集。



    def union(self, *args, **kwargs):
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)
        """
        pass

    返回两个集合的合集(合集是将两个集合元素合在一起)。



    def update(self, *args, **kwargs):
        """ Update a set with the union of itself and others. """
        pass

    将原集合与其他集合做合集操作。

 

内置数据类型的方法都是底层通过C语音实现的,因此执行效率要比用python写的相同方法高很多。写程序时能用内置方法,尽量不要自己去写,可以减少一些执行时间。

后续进行细节补充

To be continued...

 

转载于:https://www.cnblogs.com/by3333/p/7718080.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值