美文网首页
str list dict tuple set 五兄弟

str list dict tuple set 五兄弟

作者: 酷酷的图图 | 来源:发表于2018-06-25 20:08 被阅读0次

    人生苦短 我用python

    开始愉快的享(代)受(码)时间:

    • str

    字符串属于不可变类型,一旦定义就不能修改

    • 索引获取字符串内容
    info = "今天星期三hello world"
    print(info[2])
    
    • 字符串的"切片"操作
    info = "今天星期三hello world"
    print(info[2:5])
    print(info[::-1])  # TODO 字符串反转
    
    • 根据字符串查找 结果返回索引(find(), index())
    content = "张三李四王五张三"
    result = content.find("四王")  # 结果:3   注意:如果结果没找到 返回-1
    
    result = content.index("张三") #  结果:0 只返回第一个匹配的结果索引 惰性查找
    
    • 获得某个字符的个数 (count)
    content = "张三李四王五张三找刘"
    print(content.count("张三"))  #  结果:2
    
    • 字符串替换(replace)
    # replace:替换   很常用
    path = "程序员,工程师,开发人员"
    print(path.replace(",", "/"))  # 结果:程序员/工程师/开发人员
    
    • 分割( split)
    url = "http://www.baidu.com/hello.jpg"
    result = url.split("/") # 结果:返回列表, 内容为: ['http:', '', 'www.baidu.com', 'hello.jpg']
    
    • 以...开始/结束(startswith/endswith)
    # startswith   endswith  很常用
    url = "//www.baidu.com"
    if not url.startswith("http"):
        url = "http:" + url
    
    path = "baidu.jpg"
    if path.endswith(".jpg"):
        print("可以删除")
    
    • 将字符变成小写(lower)
    # lower  很常用
    content = input("请输入一个字母")
    if content == 'w' or content == 'W':
        print("输入的是w")
    
    • list

    • 创建方式
    list1 = []  或者 list1 = ['a', 'b', 'c']
    list2 = list()
    
    • 添加元素(append, insert)
    list1.append('zhangsan') #  在列表末尾追加元素
    list1.insert(2,'lisi') #  在索引为2的位置插入元素
    list1.insert(-1, "D") # 一般不会倒着插入 在倒数第二的位置插入
    
    • 查找元素(in查找 ,index)
    方式1:
    if "李四" in list1:
        print("存在")
    
    方式2:
    result_index = list1.index("李四")  # index:只会从左往右返回满足条件的第一个元素的索引
    
    方式3:
    content = list4[3] # 读取列表的索引为3的元素
    print(content)
    
    • 修改元素
    # 修改
    list1[1] = "修改后的李四"  # 将列表索引为1的元素值修改
    print(list4)
    
    • 删除元素
    list1.remove("zhangsn") # 直接删除元素(如果列表中有2个以上相同元素 只会删除从左至右的第一个)
    list1.pop() # 删除列表最后一个元素
    list1.pop(2) # 删除元素为2的元素
    
    • 列表的切片
    # 列表的切片
    list5 = ['a', 'b', 'c', 'd', 'e'] 
    print(list5[2::-1])  # 结果  ['c', 'b', 'a']
    print(list5[1:-1])   # 结果  ['b', 'c', 'd']
    print(list5[2:])     # 结果  ['c', 'd', 'e']
    print(list5[:2])     # 结果  ['a', 'b']
    print(list5[1:4:2])  # 结果  ['b', 'd']
    print(list5[::-1])   # 结果  ['e', 'd', 'c', 'b', 'a']
    print(list5[::2])    # 结果  ['a', 'c', 'e']
    print(list5[1::2])   # 结果  ['b', 'd']
    
    • 扩展列表元素(列表追加extend 拼接)
    list1 = ['a', 'b', 'c']
    list2 = ['d', 'e', 'f']
    list3 = list1 + list2 # 通过+直接拼接(缺陷:需要开辟新空间来存放数据, list1/list2/list3总共占用12个空间)
    list1.extend(list2) # 通过extend扩展(推荐,list1/list2总共占9个空间)
    print(list3)
    print(list1)
    
    • 列表推导式
    [x for x in list1 if x.startswith('zhang')]  # 将列表中满足开始位置含有''zhang'' 的字符串元素组合 生成一个新的列表
    
    • 求和(sum)
    # 求和
    list1 = [1, 3, 5, 7, 9]
    result = sum(list1)
    print(result)
    
    • tuple

    元组为不可变类型 不能执行 添加 修改 删除操作

    • 创建方式
    tuple1 = () 或者 tuple1 = (1,'2','c') # 创建空元组:因为不能添加,所以不会创建空元组
    tuple2 = tuple()
    
    • 查找元素(index)
    result_index = tuple1.index('c') # 结果:2  如果查找内容不存在 则报错
    
    item = tuple1[1] # 根据索引 获取某个元素
    print(item)
    
    • 元组 + 元组 生成新的元组
    tp3 = ('a', 'b', 'c')
    tp4 = ('d', 'e', 'f')
    print(tp3+tp4) # 结果:生成新元组('a', 'b', 'c','d', 'e', 'f')
    
    • dict

    字典和json长得比较像 (json形式的字符串 里面必须用双引号!)
    字典的key一般都是字符串,其它类型也可以,但必须是不可变类型

    • 创建方式
    dict1 = {}
    dict2 = dict()
    
    • 添加/修改元素
    dict3['class'] = "三年级二班" #  如果字典存在'key为'class'' 则表示直接对value赋值 如果不存在该key  则会先创建key 再赋值
    print(dict3) # 即: 如果key存在则修改,如果不存在则添加
    
    • 获取方式
    # 注意:字典根据key获得value的两种形式
    value = dict1['stu_id']
    value = dict1.get('stu_id', '没有名字')
    # dict1[key]: key必须存在,否则会报错,不推荐
    # dict1.get(key, default)  如果key不存在,返回默认值
    
    • 删除元素
    方式1:
    dict3.pop('age')  #  pop删除后 会将删除的内容返回
    方式2:
    del dict3["name"]
    
    • 查询
    # 查询目录
    if "hobby" in dict3.keys(): # 可以简化为 if "hobby" in dict3:
        print("目录存在")
    else:
        print("目录不存在")
    
    # 查询内容
    if 1.78 in dict3.values():
        print("内容存在")
    else:
        print("内容不存在")
    
    # 遍历 key,value
    for key,value in dict3.items():
    print(key,value)
    
    • set

    set是一个无序且不重复的元素集合。
    具体可参照链接: https://www.cnblogs.com/whatisfantasy/p/5956775.html

    集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。集合支持用in和not in操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值。

    set和dict一样,只是没有value,相当于dict的key集合,由于dict的key是不重复的,且key是不可变对象因此set也有如下特性:

    • 不重复
    • 元素为不可变对象

    *创建方式

    s = set()
    s = {11,22,33,44}  #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典
    
    a=set('boy')
    b=set(['y', 'b', 'o','o'])
    c=set({"k1":'v1','k2':'v2'})
    d={'k1','k2','k2'}
    e={('k1', 'k2','k2')}
    print(a,type(a))  # 结果: {'o', 'b', 'y'} <class 'set'>
    print(b,type(b))  # 结果: {'o', 'b', 'y'} <class 'set'>
    print(c,type(c))  # 结果:  {'k1', 'k2'} <class 'set'>
    print(d,type(d))  # 结果: {'k1', 'k2'} <class 'set'>
    print(e,type(e))  # 结果: {('k1', 'k2', 'k2')} <class 'set'>
    

    相关文章

      网友评论

          本文标题:str list dict tuple set 五兄弟

          本文链接:https://www.haomeiwen.com/subject/cqacyftx.html