python列表常用函数_Python入门教程3. 列表基本操作【定义、运算、常用函数】

前面简单介绍了Python字符串基本操作,这里再来简单讲述一下Python列表相关操作

1. 基本定义与判断

>>> dir(list) #查看列表list相关的属性和方法

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> lst = [] #定义一个空列表

>>> type(lst) #判断列表类型

>>> bool(lst) #bool()函数可判断对象真假,这里判断空列表lst为假

False

>>> print(lst)

[]

>>> a = ['1','False','jb51']

>>> type(a)

>>> bool(a)

True

>>> print(a)

['1', 'False', 'jb51']

>>>

2. 列表常用操作函数:

append()

在列表末尾追加元素

count()

统计元素出现次数

extend()

用一个列表追加扩充另一个列表

index()

检索元素在列表中第一次出现的位置

insert()

在指定位置追加元素

pop()

删除最后一个元素(也可指定删除的元素位置)

remove()

删除指定元素

reverse()

将列表元素顺序反转

sort()

对列表排序

len()

计算列表元素个数

>>> list1 = [1,2,3,4,5,6]

>>> list1.append(1)

>>> list1.count(1)

2

>>> list2 = ['Tom',7]

>>> list1.extend(list2) # 列表list1后追加列表list2

>>> list1

[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]

>>> list1.extend(['haha',8]) # 可以直接在extend函数的参数中使用列表

>>> list1

[1, 2, 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]

>>> list1.insert(2,'huhu') # 使用insert函数在序号2处添加元素'huhu'

>>> list1

[1, 2, 'huhu', 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]

>>> list1.pop() # pop()方法取出栈尾元素

8

>>> tmp = list1.pop() #可以将栈尾元素赋值便于使用

>>> tmp

'haha'

>>> list1.remove('huhu') #使用remove()函数删除指定元素'huhu'

>>> list1

[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]

>>> list1.reverse()

>>> list1

[7, 'Tom', 1, 6, 5, 4, 3, 2, 1]

>>> list1.sort() #这里使用sort()排序,但是包含字符串类型与整数类型,会报错!

Traceback (most recent call last):

File "", line 1, in

list1.sort()

TypeError: '<' not supported between instances of 'str' and 'int'

>>> list1.remove('Tom')

>>> list1.sort()

>>> list1

[1, 1, 2, 3, 4, 5, 6, 7]

>>> list1 = list(set(list1)) # 列表list去重(先使用set转换为不重复集合,再使用list类型转换回列表)

>>> list1

[1, 2, 3, 4, 5, 6, 7]

>>> l = len(list1) #使用len()方法求列表长度

>>> l

7

>>> list1.index(5) # index()获取元素出现的位置

4

简单入门教程~

基本一看就懂~O(∩_∩)O~

未完待续~~欢迎讨论!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值