• python:list和dict的基本操作实例


    python:list和dict的基本操作实例

    今天我们来谈谈Python中list和dict的使用方法。这两种数据结构在Python中非常常见,掌握它们的使用方法对于编写高效的代码非常重要。

    首先我们来看看list的使用。在下面的例子中,我们有一个名为ori_list的列表,其中包含了一些数字。我们还有另外一个名为other_list的列表,也包含了一些数字。我们可以使用append方法向ori_list中添加元素,也可以使用extend方法将other_list中的元素添加到ori_list中。另外,我们还可以使用sort方法对列表进行排序,包括倒序排序。最后,我们可以使用reverse方法将列表中的元素倒序排列。

    接下来,让我们看看dict的使用。在下面的例子中,我们有一个名为ori_dict的字典,其中包含了一些人名和对应的年龄。我们还有另外一个名为other_dict的字典,也包含了一些人名和对应的年龄。我们可以使用keys方法获取字典中所有的键,使用values方法获取字典中所有的值,使用items方法获取字典中所有的键值对。另外,我们还可以使用索引的方式向字典中增加元素,也可以使用update方法将一个字典中的元素更新到另一个字典中。

    # list的使用
    ori_list = [1, 2, 3]
    other_list = [8, 7, 6]
    # append
    ori_list.append(4)
    print(ori_list)
    
    # extend
    ori_list.extend(other_list)
    print(ori_list)
    
    # sort
    ori_list.sort()
    print(ori_list)
    
    # 直接sort时就倒序
    ori_list.sort(reverse=True)
    print(ori_list)
    
    # reverse
    ori_list.reverse()
    print(ori_list)
    
    
    # dict的使用
    ori_dict = {"张三": 18, "李四": 40, "王五": 34}
    other_dict = {"孙悟空": 500, "猪八戒": 200}
    # keys
    print(ori_dict.keys())
    
    # values
    print(ori_dict.values())
    
    # items
    print(ori_dict.items())
    
    # 增加元素
    ori_dict["赵六"] = 20
    print(ori_dict)
    
    # update
    ori_dict.update(other_dict)
    print(ori_dict)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    通过这些例子,我们可以看到list和dict在Python中的灵活运用。掌握了它们的使用方法,我们就可以更加高效地处理数据和编写代码。希望这些例子对大家有所帮助,也欢迎大家分享更多关于list和dict的使用技巧。

  • 相关阅读:
    PyTorch深度学习遥感影像地物分类与目标检测、分割及遥感影像问题深度学习优化实践技术应用
    马克思的手稿-第11届蓝桥杯Scratch选拔赛真题精选
    Kafka 为什么那么快?
    docker安装单机版redis、集群版redis
    VueCLI核心知识综合案例TodoList
    双端队列--二叉树 Z 字层序遍历
    Pandas 数据中的loc与iloc含义以及操作
    力扣-228.汇总区间
    使用iso镜像包制作离线本地镜像源(本地yum源)
    11.23二叉树
  • 原文地址:https://blog.csdn.net/fox_kang/article/details/134518670