• day4 切片,数据类型


    day5:
    序列,可以使用切片
    序列类型:字符串,列表,元祖
    特点:可以通过坐标来取值,坐标从0开始
    >>> s = "agfdagsgsdgsa"
    >>> print(s[0])
    a
    >>> print(s[1])
    g
    >>> s = [1,2,3,4,5,6]
    >>> print(s[1])
    2
    >>> print(s[0])
    1
    >>> print(s[:-1])
    [1, 2, 3, 4, 5]
    >>> print(s[-1:])
    [6]
    >>> print(s[-1])
    6
    练习:取11个元素中间的
    >>> l = list(range(11))
    >>> l[len(l)//2]
    5
    list 切片 l[1:3:1] 开始,开区间,步长,步长可以为正,也可以为负
    max,min,[1,2,3]*3
    >>> l[6:10]
    [6, 7, 8, 9]
    >>> l[::-2]
    [10, 8, 6, 4, 2, 0]
    练习:s = "gloryroad is good!" 取出road和oo并拼接起来
    >>> s = "gloryroad is good!"
    >>> s1 = s[5:9]
    >>> s1
    'road'
    >>> s2 = s[14:16]
    >>> s2
    'oo'
    >>> s1+s2
    'roadoo'
     
    判断是否是列表:
    isinstance(l,list)
    True
    增:append,insert
    a = []
    a.append(1)
    a.insert(0,2)
    删:del remove
    del a[1]
    a.remove(1) 删除的是值
    改:a[1] = 'abc'
    查:
    a.pop(1) 弹出
     
    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> a.append(b) append 是追加的模式
    >>> a
    [1, 2, 3, [4, 5, 6]]
    >>> a.extend(b) extend 会把list拆分,然后在组合,而不是当成一个list整体加入到a当中
    >>> a
    [1, 2, 3, [4, 5, 6], 4, 5, 6]
     
     
    元祖 tuple 元祖不能改,不能添加不能修改,取值方法和列表一样
    b = (1,2,3)
    >>> isinstance(b,tuple)
    [0, 1, 2, [4, 5, 6]]
    >>> aa[3].append(7)
    >>> aa
    [0, 1, 2, [4, 5, 6, 7]]
    >>> aa[3].remove(6)
     
    字典:Key 是唯一的
    d = {}
    d[1] = 'a'
    d[2] = 'b'
    dict(a=1,b=2,c="3")
     
    del d[1]
     
    list(d.items())
    for i in d.keys():
    print(i)
     
    for i in d.values():
    print(i)
    for i,m in d.items():
    print(i,":",m)
    list(d.items())
     
    练习:
    1.求全部元素的和 [1,2,1,2,3,3,3,3] 遍历
    a = [1,2,1,2,3,3,3,3]
    sum = 0
    n = len(a)-1
    while n>=0:
    sum+=a[n]
    n-=1
    关键点:n = len(a)-1 获取到列表的最后一个值,此时n=7 a[7]=3,因为n>7满足while条件,所以sum=0+3,然后n=7-1 接着执行while,直到n=0,0-1<0时结束
    2.求偶数元素的和 [1,2,1,2,3,3,3,3] 切片
    a = [1,2,1,2,3,3,3,3]
    aa = []
    for i in a:
    if i%2 == 0:
    aa.appen(i)
    sum = 0
    n = len(aa)-1
    while n>=0:
    sum+=aa[n]
    n-=1
    3.统计所有数字出现的个数 [1,2,1,2,3,3,3,3] 字典
    a = [1,2,1,2,3,3,3,3]
    f = {}
    for i in a:
    f[i]=0
    len(f)

  • 相关阅读:
    yum提示another app is currently holding the yum lock;waiting for it to exit
    关于CentOS下 yum包下载下的rpm包放置路径
    Linux查看History记录加时间戳小技巧
    swift能干什么,不能干什么及相关概念
    yum改成网易的源
    dd测试硬盘性能
    对象存储
    IDEA的常用快捷键
    httpFS访问
    关于hadoop: command not found的问题
  • 原文地址:https://www.cnblogs.com/jueshilaozhongyi/p/12081942.html
Copyright © 2020-2023  润新知