zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    团队作业第五次—项目冲刺-Day6
    团队作业第五次—项目冲刺-Day4
    团队作业第五次—项目冲刺-Day3
    团队作业第五次—项目冲刺-Day2
    研途——冲刺集合
    团队作业第六次—事后诸葛亮
    研途——测试总结
    研途——冲刺总结
    研途——冲刺日志(第七天)
    研途——冲刺日志(第六天)
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11102598.html
Copyright © 2011-2022 走看看