zoukankan      html  css  js  c++  java
  • 列表、元组、字典、集合

    列表(List)

    一. 列表

    1.列表介绍

      列表是一种数据类型,由[ ]括起来,里面的元素由","隔开列表可以右增删修改查询的操作.列表里可以有数字,字符串,列表,元组,字典等不同类型的数据.

      例如:lst = [12,"hello",["good","morning",26],("way","Jack"),{"element":"元素","roof":"房屋"},"computer","CPU"]

    2.索引和切片

      1) 索引

      语法:lst[下标],和字符串一样.

    lst = [12,"hello","way","Jack","element","roof","computer","CPU"]
    print(lst[0]) #12
    print(lst[1]) #hello
    print(lst[2]) #way
    print(lst[5]) #roof
    print(lst[15]) #list index out of range 超出列表的范围,报错.

      2) 切片

      语法:lst[start:end:步数(int型)],从左往右切范围[:],从右往左切范围[-1:]. start是列表开始的下标,为空时表示从头开始切, end是列表中结束的下标,为空时表示切到尾(包括尾). 步数是每隔几个取一个,有方向,正的表示从左往右,负值表示从右往左.没有步数值时,默认从左往右获取.切片顾头不顾尾,取不到结束位置的元素,只能取到结束位置元素的前一个.

    lst = [12, "hello", "way", "Jack", "element", "roof", "computer", "CPU"]
    print(lst[0:1])       # [12]
    print(lst[:])         # [12, 'hello', 'way', 'Jack', 'element', 'roof', 'computer', 'CPU']
    print(lst[2::2])      # ['way', 'element', 'computer']
    print(lst[2:-2:2])    # ['way', 'element']
    print(lst[-2:-7:-3])  # ['computer', 'Jack']

    二 .列表的增删改查

    1. 增加

      列表的增加操作有append(),insert(),extend()这三个方法,其中append()是用的最多.

      append(): 在列表的后面直接增加元素

      insert(): 在列表的指定位置插入元素

      extend(): 迭代添加

     
    lst = [12, "hello", "way", "CPU"]
    lst.append("finish")
    print(lst)  #lst变成 [12, 'hello', 'way', 'CPU', 'finish']
    lst.insert(1,"world")
    print(lst)  #"world"被插入下标为1的"hello"后面. [12, 'world', 'hello', 'way', 'CPU', 'finish']
    
    lst1 = ["way", "Jack", "element", "roof", "computer"]
    lst1.extend("你真棒")
    print(lst1)  #['way', 'Jack', 'element', 'roof', 'computer', '你', '真', '棒']
    lst1.extend(["你真棒"])
    print(lst1)  #['way', 'Jack', 'element', 'roof', 'computer', '你', '真', '棒','你真棒']

    2. 删除

    pop(索引下标):删除指定位置的元素,没有给值时,默认删除最后一个元素.

    remove(): 删除指定元素.

    clear(): 清空列表

    del lst[start:end:步数 ]:切片删除

    lst1 = ["way", "Jack", "element", "roof", "computer"]
    lst1.pop(2)
    print(lst1)  #删除所以下标为2的"element"
    
    lst2 = [12, "hello", "way", "CPU"]
    lst2.remove("way")
    print(lst2)  #[12, 'hello', 'CPU']
    # lst2.remove("way")
    print(lst2)  #找不到"way",所以报错
    
    lst3 = ["well","good","better","best"]
    del lst3[0:2]
    print(lst3)  #['better', 'best']
    
    lst1.clear()
    lst2.clear()
    lst3.clear()
    print(lst1)  #[]
    print(lst2)  #[]
    print(lst3)  #[]

    3. 修改

       索引切片修改

    lst1 = ["way", "Jack", "element", "roof", "computer"]
    lst1[1] = "Tom"
    print(lst1)  #['way', 'Tom', 'element', 'roof', 'computer']
    
    lst2 = [12, "hello", "way", "CPU"]
    lst2[1:4:2] = ["iPhone","Android"] 
    #步数为2指每隔两个取一个,[1:4]里可取"Jack","roof"两个元素,修改的元素也要为两个.
    print(lst2)  #[12, 'iPhone', 'way', 'Android']

    4. 查询

     列表是一个可迭代对象, 所以可以进行for循环

    lst1 = ["way", "Jack", "element", "roof", "computer"]
    for c in lst1: #把lst1的元素赋给c
        print(c)
    # way
    # Jack
    # element
    # roof
    # computer

     5. 其他操作

    lst1 = ["way", "Jack", "element", "roof", "computer","roof"]
    print(lst1.count("roof"))  #2
    print(lst1.count("way"))   #1
    lst1.reverse()  #表示翻转,元素从后往前排列
    print(lst1)  #['roof', 'computer', 'roof', 'element', 'Jack', 'way']
    
    lst4 = [5,9,2,18,11,15,6]
    lst4.sort()  #升序
    print(lst4)  #[2, 5, 6, 9, 11, 15, 18]
    lst4.sort(reverse = True)  #降序
    print(lst4)  #[18, 15, 11, 9, 6, 5, 2]
    print(len(lst4))  #7 求列表长度

    三 .列表的嵌套

     降维操作,先当做一层来看

    lst = ["roof", "computer", ["way", "Jack",["computer","roof"] ,"element"]]
    print(lst[2][2][0])  #computer
    
    lst[2][1] = lst[2][1].lower()  
    #把Jack全小写,注意改变了字符串"Jack"的值,因为字符串本身不可变,所以要赋值给lst[2][1]
    print(lst)  #['roof', 'computer', ['way', 'jack', ['computer', 'roof'], 'element']]
    lst[1] = "CPU"
    print(lst)  #['roof', 'CPU', ['way', 'jack', ['computer', 'roof'], 'element']]

    元组(Tuple)

    一 .元组和元组嵌套

      元组: 俗称不可变的列表.⼜又被成为只读列表, 元组也是python的基本数据类型之一, ⽤用⼩小括 号括起来, 里面可以放任何数据类型的数据,  查询可以. 循环也可以. 切片也可以. 但就是不能改.用()括起来,元素用逗号,隔开.元组中只有一个元素时要添加逗号,否则不是元组.例如: (1,)

    1. 索引和切片

    tu = ("way", "Jack", "element", "roof", "computer")
    print(tu [2])  #element
    print(tu[1:4])  #('Jack', 'element', 'roof') 切片过后还是元组.

    2 .遍历元组

    tu = ("way", "Jack", "element", "roof", "computer")
    for c in tu:
        print(c)
    # way
    # Jack
    # element
    # roof
    # computer

    3.修改元组

    tu = ("way", "Jack", "element",[], "roof", "computer")
    tu[1] = "Tom"
    print(tu)  #无法修改,结果报错.
    
    tu[1] = tu[1].replace("Jack","Tom")
    print(tu)  #无法修改,报错.
    
    tu[3].append("because")
    print(tu)  #('way', 'Jack', 'element', ['because'], 'roof', 'computer')

    五.range

       range可以帮我们获取到一组数据. 通过for循环能够获取到这些数据.

    for c in range(5):  #从0数到4
        print(c)  #从0打印到4
    # 0
    # 1
    # 2
    # 3
    # 4
    for c in range(15,3,-2):  #从15数到2,每隔两个取一个
        print(c)  #从15到2,每隔两个打印一个
    # 15
    # 13
    # 11
    # 9
    # 7
    # 5

    字典(Dict)

    一. 字典的简单介绍

      字典是{}括起来的键值对组成dict = {key1:value1,key2:value2,...}. 在dict中key是唯一的. 在dict中的key必须是不可变的. dict保存的数据不是按照我们添加进去的顺序保存的.

    dic = {"one":1, "two":2, "three":3}
    dic["four"] = 4  #把"four":4添加进字典
    print(dic)  #{'one': 1, 'two': 2, 'three': 3, 'four': 4}.  

    dic = {["work","job"]:"long"}
    print(dic)  #TypeError: unhashable type: 'list'  list是可变的不能作为key

    二. 字典的增删改查和其他操作

    1. 增加

    dic = {"one":1, "two":2, "three":3}
    dic["four"] = 4  #把"four":4添加进字典
    print(dic)  #{'one': 1, 'two': 2, 'three': 3, 'four': 4}.

    dic = {"one":1, "two":2, "three":3}
    dic["two"] = "二"  #当key重复时,会更新value的值
    print(dic)  #{'one': 1, 'two': '二', 'three': 3}
    
    
    dic = {"one":1, "two":2, "three":3}
    dic.setdefault("five",5) #把key值为"five",value值为5.添加到dic字典里
    print(dic)  #{'one': 1, 'two': 2, 'three': 3, 'five': 5}
    dic.setdefault("six",6)
    print(dic)  #{'one': 1, 'two': 2, 'three': 3, 'five': 5,'six': 6}
    dic.setdefault("six",7)  #已经有key值为"six",所以此次不存储
    print(dic)  #{'one': 1, 'two': 2, 'three': 3, 'five': 5, 'six': 6}

    2.删除

      pop(key)       通过key值删除,删除一个元素. 返回这个元素的value值

      del dic[key]   通过key值删除

      popitem()      随机删除,删除一个元素. 返回一个元组

      clear()           清空字典

    dic = {"one":1, "two":2, "three":3}
    ret = dic.pop("two")  #删除key值为"two"的元素
    print(dic)  #{'one': 1, 'three': 3}
    print(ret)  #2 key值为"two"的value为2 
    dic = {"one":1, "two":2, "three":3}
    del dic["one"]
    print(dic)  3{'two': 2, 'three': 3}
    dic = {"one":1, "two":2, "three":3}
    a = dic.popitem()
    print(a)  #('three', 3)  返回的是一个元组
    print(dic)  #{'one': 1, 'two': 2}
    dic = {"one":1, "two":2, "three":3}
    dic.clear()
    print(dic)  #{}

    3. 修改

       update()是更新的意思,可以在两个字典里,把一个字典的元素更新到另一个字典里.不同的key值,直接把元素添加到另一个字典中,若有相同的key值,则把value值覆盖.达到了修改的作用.

    dic1 = {"one": 1, "two": 2, "three": 3, "four": "四"}
    dic2 = {"one": "一", "four": 4, "five": 5, "two": "二"}
    dic3 = {"five": "五", "six": "六", "seven": 7}
    dic1.update(dic2)
    dic2.update(dic3)
    dic3.update(dic2)
    print(dic1)  #{'one': '一', 'two': '二', 'three': 3, 'four': 4, 'five': 5}
    print(dic2)  #{'one': '一', 'four': 4, 'five': '五', 'two': '二', 'six': '六', 'seven': 7}
    print(dic3)  #{'five': '五', 'six': '六', 'seven': 7, 'one': '一', 'four': 4, 'two': '二'}

    4.查询

      可以直接查询dic[key],也可以用get(key)和setdefault(key,value).

    dic1 = {"one": 1, "two": 2, "three": 3, "four": "四"}
    print(dic1["four"])  #四
    print(dic1.get("on"))  #None  找不到key值,返回None,也可以自己设置返回值dic1.get(key,返回值).
    ret = dic1.setdefault("five",5)
    print(dic1)  #{'one': 1, 'two': 2, 'three': 3, 'four': '四', 'five': 5}
    print(ret)  #5

     5. 其它相关操作

      keys()    打印出所有的key值

      values() 打印出所有的value值

      items()   打印出所有键值对.

    dic = {"name":"tom","sex":"male","age":25,"job":"actor"}
    print(dic.keys())  #dict_keys(['name', 'sex', 'age', 'job'])  高仿列表,不是列表
    for c in dic.keys():
        print(c)
    # name
    # sex
    # age
    # job
    dic = {"name":"tom","sex":"male","age":25,"job":"actor"}
    print(dic.values())  #dict_values(['tom', 'male', 25, 'actor'])
    for c in dic.values():
        print(c)
    # tom
    # male
    # 25
    # actor
    dic = {"name":"tom","sex":"male","age":25,"job":"actor"}
    print(dic.items())  #dict_items([('name', 'tom'), ('sex', 'male'), ('age', 25), ('job', 'actor')])
    for c in dic.items():
        print(c)
        # ('name', 'tom')
        # ('sex', 'male')
        # ('age', 25)
        # ('job', 'actor')
        print(c[0])  #打印元组c的第一个元素
        print(c[1])  #打印元组c中的第二个元素

    key,value = ("name", "tom")
    print(key)  #name
    print(value)  #tom
    #key,value对应name,tom,我们key把上面for循环的c直接换成key,value
    for key,value in dic.items():
        print(key,value)
    # name tom
    # sex male
    # age 25
    # job actor
    
    
    

    三. 字典的嵌套

      字典的嵌套是通过找key值来打印出value值,先从最外层找起.

    dic = {"time":8,"place":"park","people":{"name":"tom","sex":"male","age":20}
        ,"food":{"China":"rice","America":"steak","Britain":"tea"}}
    
    print(dic["people"]["sex"])  #male
    print(dic["food"]["Britain"])  #tea 

    集合(Set)

    
    

      set集合是python的一个基本数据类型. 一般不是很常⽤用. set中的元素是不重复的.无序的.里面的元素必须是可hash的(int, str, tuple,bool), 我们可以这样来记. set就是dict类型的数据但是不保存value, 只保存key. set也用{}表示.

       注意: set集合中的元素必须是可hash的, 但是set本身是不可hash得. set是可变的

    
    
    s = {123, {1,2,3}}    
    print(s)  # 不合法 TypeError: unhashable type: 'set'

    1. set集合的增删改查

      (1) 增加

    s = {'an','empty','street'}
    s.add('sky')
    print(s)  #{'sky', 'an', 'empty', 'street'}
    
    s = {'an','empty','street'}
    s.update('sea')  #迭代添加
    print(s)  #{'s', 'a', 'e', 'street', 'an', 'empty'}
    
    s = {'an','empty','street'}
    s.update(['sea'])
    print(s)  #{'an', 'street', 'sea', 'empty'}
    
    

      (2) 删除

    
    
    s = {'an','empty','street'}
    ret = s.pop()  #随机删除
    print(ret)  #返回删除的元素:empty
    print(s)  #{'street', 'an'}
    
    s = {'an','empty','street'}
    s.remove('an')  #删除指定元素
    print(s)  #{'empty', 'street'}
    s.remove('one')  #没有one这个元素,会报错
    
    s = {'an','empty','street'}
    s.clear()
    print(s)  #set()

      (3) 修改 

      set集合中的数据没有索引,也没有办法去定位一个元素.所以没有办法进行直接修改,我们可以采用先删除后添加的方式来完成修改操作.

    s = {'an','empty','street'}
    s.remove('an')  #先删除'an'
    s.add('one')  #再添加'one'
    print(s)  #{'one', 'empty', 'street'}
    
    

      (4) 查询 

       set是一个可迭代对象. 所以可以进行for循环

    s = {'an','empty','street'}
    for c in s:
        print(c)
    # an
    # empty
    # street

    2. 常用操作

    s1 = {'an','empty','street'}
    s2 = {'the','empty','house'}
    #交集
    print(s1 & s2)  #{'empty'}
    #并集
    print(s1 | s2)  #{'an', 'the', 'house', 'empty', 'street'}
    #差集
    print(s1 - s2)  #{'an', 'street'}
    # 反交集
    print(s1 ^ s2)  #{'an', 'street', 'house', 'the'}
    set集合本身是可以发生改变的.是不可hash的. 我们可以使用frozenset来保存数据. frozenset是不可变的. 也就是一个可哈希的数据类型.
    s = frozenset({'an','empty','street'})
    dic = {'hello':s}
    print(dic)  #{'hello': frozenset({'empty', 'street', 'an'})}
    
    
    无限的我,现在才开始绽放,从东边的第一缕阳光到西边的尽头
  • 相关阅读:
    C++——"%"运算符
    九度教程第22题——今年暑假不AC(看尽量多的电视节目)
    C++标准模板库 ——堆栈使用
    .Net转Java自学之路—基础巩固篇十三(集合)
    .Net转Java自学之路—基础巩固篇十二(多线程)
    .Net转Java自学之路—基础巩固篇十(异常)
    .Net转Java自学之路—基础巩固篇九(Object、内部类)
    .Net转Java自学之路—基础巩固篇八—总结(封装、继承、多态)
    .Net转Java自学之路—基础巩固篇七(接口、多态)
    .Net转Java自学之路—基础巩固篇六(继承)
  • 原文地址:https://www.cnblogs.com/huangqihui/p/9270759.html
Copyright © 2011-2022 走看看