• python-list一些用法


    1、#问题1:判断某个元素是否存在容器中
    #关键字 in & not in
    list=[1,2,3]
    print(1 in list)
    print(1 not in list)

    2:求解元素出现的次数「内置函数count("询问的元素")」
    list=[1,2,3,4,4,5]
    print(list.count(4))

    3、查找字符串出现的位置、索引「index("询问的元素")」,不存在时会报错

    list=[1,2,3,4,4,5]
    print(list.index(4))

    4、求解列表里元素之和「内置函数sum用于求解元素之和,有返回值」
    list=[1,2,3,4,4,5]
    a =sum(list)
    print(a)

    5、元素排序:
    a、「sort()方法」,默认正序,可不传参,倒序:list.sort(reverse=True) 倒序,True注意大写

    list=[1,2,3,4,4,5]
    list1=list.sort()
    print(list)[可正常输出排序列表]
    print(list1)[这里会输出none,sort方法没有返回值,只是在原列表排序,原list会发生改变]

    b、sorted()函数 。list1=sorted(list,reverse=True)

    list=[1,2,3,55,4,4,5]

    list1=sorted(list)
    print(list)//输出原列表[1,2,3,55,4,4,5]
    print(list1)//输出排序后的列表

    --- list.sort()没有返回值,不改变了原来的列表。sorted内置函数有返回值(),会新产生一个列表,不改变原来的list
    -- list列表字符串排序,根据字母顺序排序,字符串和整数之间不能排序。

    6、列表推导式>>>python中列表推导式用于使用其他列表创建一个新列表。

    其基本形式为: [表达式 for 变量 in 列表]  

    new_list=[x*2 for x in range(0,10,2)]
    print(new_list)//[0, 4, 8, 12, 16]


    二维列表推导式:
    example2 = [[10,20,30],[40,50,60],[70,80,90],[100]]
    example3 = [j**2 for i in example2 for j in i if j%2 == 0]
    print(example3)//[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100, 10000]


    list=[[j for j in range(4)]for x in range(5)]
    print(list)//输出[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

     

    
    
  • 相关阅读:
    LeetCode——4Sum
    LeetCode——3Sum
    LeetCode——Longest Repeating Character Replacement
    LeetCode——Longest Palindromic Subsequence
    LeetCode——Longest Word in Dictionary through Deleting
    剑指Offer——丑数
    剑指Offer——最长不包含重复字符的子字符串
    剑指Offer——把数组排成最小的数
    LAMP第四部分mysql操作
    LAMP第三部分php,mysql配置
  • 原文地址:https://www.cnblogs.com/Huangzena/p/11639175.html
Copyright © 2020-2023  润新知