• python学习-17 列表list 2


    # 1. 选择嵌套列表里的元素(内部进行了for循环)


    li = [1,2,"age",["熊红","你好",["12",45]],"abc",True] a = li[3][2][1] print(a)

    运行结果:

    45
    
    Process finished with exit code 0

    #2. 字符串转换列表

    a = "iamchinese"
    b =list(a)
    print(b)

    运行结果:

    ['i', 'a', 'm', 'c', 'h', 'i', 'n', 'e', 's', 'e']
    
    Process finished with exit code 0

    #3. 列表转换字符串

    第一种方法:(for循环)

    li =[123,456,"abcdefg"]
    b = " "
    for a in li:
       b=b+str(a)
    print(b)

    运算结果:

    123456abcdefg
    
    Process finished with exit code 0

    第二种方法:(列表中的元素只有字符串时)

    li =["abcdefg"]
    a ="".join(li)
    print(a)

    运行结果:

    abcdefg
    
    Process finished with exit code 0

    #4. list 的其他功能

    -追加(也可以加字符串,列表等)

    li = [123,13121,55]
    li.append(6)
    print(li)

    运算结果:

    [123, 13121, 55, 6]
    
    Process finished with exit code 0

    -清空

    li = [123,13121,55]
    li.clear()
    print(li)

    运算结果:

    []
    
    Process finished with exit code 0

    -浅拷贝

    li = [123,13121,55]
    a = li.copy()
    print(li)
    print(a)

    运算结果:

    [123, 13121, 55]
    [123, 13121, 55]
    
    Process finished with exit code 0

    -计数

    li = [55,123,13121,55]
    a =li.count(55)         #计算 55 出现过几次
    
    print(a)

    运算结果:

    2
    
    Process finished with exit code 0

    -迭加

    li = [1,2,3,4,5]
    li.extend([7,8,9,"你好"])
    
    print(li)

    运算结果:

    [1, 2, 3, 4, 5, 7, 8, 9, '你好']
    
    Process finished with exit code 0

    ps: append 将整个元素添加, extend 是内部经过for循环将一个添加

    -获取位置

    li = [1,22,33,4,5,33]
    a
    =li.index(33) #(从左向右获取索引位置(获取到第一个就不会继续了),可以指定位置li.index(0:3)) print(a)

    运算结果:

    2           #(索引,不是数量)
    
    Process finished with exit code 0

    -删除某个元素并获取删除的元素

    li = [1,22,33,4,5,33]
    a=li.pop()             #  可以指定索引位置(不指定索引,默认删除最后一个)
    print(li)
    print(a)

    运算结果:

    [1, 22, 33, 4, 5]
    33
    
    Process finished with exit code 0

    -删除指定元素

    li = [1,22,33,4,5,33]
    li.remove(33)    #从左向右只删除第一个
    print(li)

    运算结果:

    [1, 22, 4, 5, 33]
    
    Process finished with exit code 0

    -反转

    li = [1,22,33,4,5,33]
    li.reverse()
    print(li)

    运算结果:

    [33, 5, 4, 33, 22, 1]
    
    Process finished with exit code 0

    -排序

    li = [1,22,33,4,5,33]
    li.sort(reverse=True)        # 括号里不填默认从小到大排序
    print(li)

    运算结果:

    [33, 33, 22, 5, 4, 1]
    
    Process finished with exit code 0
  • 相关阅读:
    vue之插槽
    微信公众号-关注和取消关注
    微信公众号-消息响应
    微信公众号-验证接入
    微信公众号-开发工具natapp内网穿透安装和使用
    windows安装PHP5.4+Apache2.4+Mysql5.5
    php各种主流框架的优缺点总结
    php框架的特性总结
    什么是php?php的优缺点有哪些?与其它编程语言的优缺点?
    二进制、八进制、十进制、十六进制之间转换
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11102598.html
Copyright © 2020-2023  润新知