fqy131314

Python——列表的常用操作

1.append:

 

        cities = ['北京']

        cities.append('上海')

 

2.count:统计某个元素在泪飙中出现的次数

        temps = ['to','be','or','not','to','be']

        print(temps.count('to'))

3.extend:将一个列表中元素追加到另外一个列表中

        a = [1,2,3]

        b = [4,5,6]

        c = a.extend(b)

4.insert:将某个值插入到列表中的某个位置:

        chars = ['hello','world']

        chars.insert(1,'nihao')

5.pop方法:移除列表中最后一个元素,并且返回该元素的值:

        x = [1,2,3]

        temp = x.pop()  #返回3

6.remove方法:移除列表中第一个匹配的元素,不会返回这个被移除的元素的值。如果被移除的这个值不存在列表中,则会抛出一个异常。

7.sort:将列表中的元素进行排序,会更改原来列表中的位置

        x = [4,2,1,5,3]

        x.sort()

        print(x)

8.del关键字:根据下标删除元素:

        a = [1,2,3]

        del a[0]

        print(a) # [2,3]

9.使用in判断列表中是否有某个元素:

        x = [1,2,3]

        if    i    in   x :

                print(True)

        else:

                print(False)

10.list函数:将其他的数据类型转换成列表:

        a = 'hello'

        print( list(a) )

# 字符串补充知识

        tmp_str = "1,2,3,4,5"

        print(tmp_str)

        print( type(tmp_str) )

#字符串转数组

        print( list(tmp_str) )

         print(tmp_str.split(",")

数组转换字符串

        print("*" * 50)
        tmp_list5 = ["a","b","c"]
        print('.'.join(tmp_list5))

运行结果:

                a.b.c

posted on 2022-12-14 10:25  会飞的鱼-blog  阅读(33)  评论(0)    收藏  举报  来源

导航