Python-Class 4___列表、元组、字典的操作

本文详细介绍Python中列表、元组和字典的基本操作方法,包括创建、增删改查等核心功能,并提供具体实例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

目录

一、列表

1.0、创建列表

1.1、append

1.2、clear

1.3、copy 

1.4、count 

1.5、extend

1.6、index

1.7、insert

1.8、pop

1.9、remove 

1.10、reverse

1.11、sort

1.12、切片

二、元组

2.0、创建元组

2.1、count

2.2、index

三、字典

3.0、创建字典

3.1、clear

3.2、copy

3.3、fromkeys

3.4、get

3.5、items

3.6、keys

3.7、pop

3.8、popitem

3.9、setdefault

3.10、update

3.11、values


一、列表

Python默认库中的“list”类提供了11种对列表的操作方式

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        """ 在列表末尾新增一个元素 """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        """ 清空列表 """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        """ 将列表浅复制一份 """
        return []

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        """ 返回列表中元素出现的次数 """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        """ 将列表进行扩展,实参为另一个列表 """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        """ 返回列表值的索引,如果存在多个元素,取第一个元素的索引 """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        """ 在传入值的前面插入一个元素 """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        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

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        """ 删除列表中一个元素,如果列表中存在多个元素,则删除第一个 """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        """ 反转 """
        pass

    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        """ 排序,Python3支持不同类型的排序,排序规则为:特殊字符、数字、大写、小写 """
        pass

1.0、创建列表

name = ["fixzhang","man","Love","World",24,"BiBi"]
a = ["I","Love","U"]
b = ["0","7","21"]
c = ["This",["is","copy"]]

1.1、append

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>name.append("GAGA")
>>print(name)
['fixzhang', 'man', 'Love', 'World', 24, 'BiBi', 'GAGA']

1.2、clear

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>print(name)
['fixzhang', 'man', 'Love', 'World', 24, 'BiBi']
>>name.clear()
>>print(name)
[]

1.3、copy 

>>c = ["This", ["is", "copy"]]
>>d = c.copy()
>>print(d)
['This', ['is', 'copy']]

1.4、count 

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi", "man"]
>>print(name.count("man"))
2

1.5、extend

方法一:

>>a = ["I", "Love", "U"]
>>b = ["0", "7", "21"]
>>a.extend(b)
>>print(a)
['I', 'Love', 'U', '0', '7', '21']

方法二:

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>a = ["I", "Love", "U"]
>>b = ["0", "7", "21"]
>>a += b
>>print(a)
['I', 'Love', 'U', '0', '7', '21']

1.6、index

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi", "man"]
>>print(name.index("Love"))
2

1.7、insert

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>name.insert(1, "HaHa")
>>print(name)
['fixzhang', 'HaHa', 'man', 'Love', 'World', 24, 'BiBi']

1.8、pop

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>name.pop(-2)
>>print(name)
['fixzhang', 'man', 'Love', 'World', 'BiBi']

1.9、remove 

>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi", "man"]
>>name.remove("man")
>>print(name)
['fixzhang', 'Love', 'World', 24, 'BiBi', 'man']

1.10、reverse

>>name = ["fixzhang", "man", "Love", "World", "24", "BiBi"]
>>name.reverse()
>>print(name)
['BiBi', '24', 'World', 'Love', 'man', 'fixzhang']

1.11、sort

>>name = ["fixzhang", "man", "Love", "World", "24", "BiBi"]
>>name.sort()
>>print(name)
['24', 'BiBi', 'Love', 'World', 'fixzhang', 'man']

1.12、切片

# 取下标1至下标4之间的元素,包括1,不包括4
>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>print(name[1:4])
['man', 'Love', 'World']
-------------------------------------------------------------
# 从头开始取,或者到结尾,0可以忽略,结尾要想包含必须只能填
>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>print(name[:])
['fixzhang', 'man', 'Love', 'World', 24, 'BiBi']
-------------------------------------------------------------
# 根据步长取值,从左往右,步长为2取元素
>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>print(name[::2])
['fixzhang', 'Love', 24]
-------------------------------------------------------------
# 根据步长取值,从右往左,步长为2取元素
>>name = ["fixzhang", "man", "Love", "World", 24, "BiBi"]
>>print(name[::-2])
['BiBi', 'World', 'man']

二、元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表。Python默认库中的“tuple”类提供了3种对列表的操作方式。

class tuple(object):
    """
    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): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        """ 返回列表中元素出现的次数 """
        return 0

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        """ 返回列表值的索引,如果存在多个元素,取第一个元素的索引 """
        return 0

2.0、创建元组

name = ("fix zhang","man","Love","World",24,"BiBi")

2.1、count

>>name = ("fix zhang", "man", "Love", "World", 24, "BiBi")
>>print(name.count("man"))
1

2.2、index

>>name = ("fix zhang", "man", "Love", "World", 24, "BiBi")
>>print(name.index("man"))
1

三、字典

    字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

    特点:

  • 无序
  • Key是唯一的,所以天生去重
class dict(object):
    """
    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): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    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

    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        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

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

    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

    def update(self, E=None, **F): # known special case of dict.update
        """
        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

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass

3.0、创建字典

3.1、clear

>>info = {
            "stu1101":"zhang san",
            "stu1102":"li si",
            "stu1103":"xiao ming",
         }
>>info.clear()
>>print(info)
{}

3.2、copy

>>info = {
            "stu1101":"zhang san",
            "stu1102":"li si",
            "stu1103":"xiao ming",
         }
>>aa = info.copy()
>>print(aa)
{'stu1101': 'zhang san', 'stu1102': 'li si', 'stu1103': 'xiao ming'}

3.3、fromkeys

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
       }
>>print(info.fromkeys("stu1103", "hello"))
{'s': 'hello', 't': 'hello', 'u': 'hello', '1': 'hello', '0': 'hello', '3': 'hello'}

3.4、get

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
       }
>>print(info.get("stu1101"))
zhang san
>>print(info.get("stu1104"))
None

3.5、items

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
       }
>>print(info.items())
dict_items([('stu1101', 'zhang san'), ('stu1102', 'li si'), ('stu1103', 'xiao ming')])

3.6、keys

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
         }
>>print(info.keys())
dict_keys(['stu1101', 'stu1102', 'stu1103'])

3.7、pop

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
         }

>>info.pop("stu1101")
>>print(info)
{'stu1102': 'li si', 'stu1103': 'xiao ming'}

也可以使用“del”来删除

>>info = {
            "stu1101":"zhang san",
            "stu1102":"li si",
            "stu1103":"xiao ming",
         }
>>del info["stu1101"]
>>print(info)
{'stu1102': 'li si', 'stu1103': 'xiao ming'}

3.8、popitem

>>info = {
            "stu1101":"zhang san",
            "stu1102":"li si",
            "stu1103":"xiao ming",
         }
>>info.popitem()
>>print(info)
{'stu1101': 'zhang san', 'stu1102': 'li si'}

3.9、setdefault

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
         }
>>info.setdefault("stu1104", "wang wu")
>>print(info)
{'stu1101': 'zhang san', 'stu1102': 'li si', 'stu1103': 'xiao ming', 'stu1104': 'wang wu'}
--------------------------------------------------------------------------------
>>info.setdefault("stu1103", "wang wu")
>>print(info)
{'stu1101': 'zhang san', 'stu1102': 'li si', 'stu1103': 'xiao ming'}

3.10、update

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
         }
>>info2 = {
            "1": "zhang san",
            "stu1103": "小明",
          }
>>info.update(info2)
>>print(info)
{'stu1101': 'zhang san', 'stu1102': 'li si', 'stu1103': '小明', '1': 'zhang san'}

3.11、values

>>info = {
            "stu1101": "zhang san",
            "stu1102": "li si",
            "stu1103": "xiao ming",
       }
>>print(info.values())
dict_values(['zhang san', 'li si', 'xiao ming'])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值