python之列表常用的方法和函数总结

方法:

1、list.count()统计:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list_count = list.count(4)  # 统计某个元素在列表中出现的次数
print("4 在列表中出现过 %s 次" % list_count)

4 在列表中出现过 2 次

2、list.append()添加对象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.append("obj")  # 在列表末尾添加新的对象,append添加元素不改变数据结构属性
print(list)

[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 'obj']

3、list.extend()扩展列表:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list1 = [123, 456, 789]
list.extend(list1)  # 扩展列表,在列表末尾一次性追加另一个列表中的多个值(相当于把list1的元素复制到了list)
print(list)

[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 123, 456, 789]

 

4、list.pop()删除对象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.pop(1)#移出列表中的一个元素,(默认最后一个元素)
print(list)

[6, 5, 2, 744, 1, 76, 13, 8, 4]

 

5、list.remove()删除匹配项:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.remove(4)  # 移除列表中某个值的第一个匹配项(只会移出第一个)
print(list)

[6, 5, 2, 744, 1, 76, 13, 8, 4]

 

6、list.insert()插入对象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.insert(3, "test")#将对象插入列表的第三个位置
print(list)

[6, 4, 5, 'test', 2, 744, 1, 76, 13, 8, 4]

 

7、list.copy复制列表:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list1 = list.copy()    # 复制一个副本,原值和新复制的变量互不影响
print(list1)

[4, 8, 13, 76, 1, 744, 2, 5, 4, 6]

 

8、list.reverse()反向排序:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.reverse()  # 反向列表中元素
print(list)

[4, 8, 13, 76, 1, 744, 2, 5, 4, 6]

 

9、list.index()获取索引:

# 修改第一个获取到对象
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list_index = list.index(4)  # 从列表中找出某个值第一个匹配项的索引位置
list[list_index] = 999 #将我们获取到的索引给他修改为999
print(list)

[6, 999, 5, 2, 744, 1, 76, 13, 8, 4]

 

# 修改所有获取到对象
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
for i in range(list.count(4)):  # 用列表的方法count找到有多少元素等于4,然后for在来循环
    list_index = list.index(4)  # 找到的每一个4都用来赋给list_index
    list[list_index] = 999  # 最后将最后将我们获取到的索引改为999
    print(list)   # print我放入了for循环里面,所以输出了两条,但是从这里我们可以看到,第一次改了第一个4,第二次改了第二个4

[6, 999, 5, 2, 744, 1, 76, 13, 8, 4]
[6, 999, 5, 2, 744, 1, 76, 13, 8, 999]

 

 

10、list.sort()排序:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.sort()#对原列表进行排序.根据ascii排序
print(list)

[1, 2, 4, 4, 5, 6, 8, 13, 76, 744]

 

11、list[obj]步长:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(list[0:-1:2])  # 这个被称为步长,最后一个2代表每隔2个元素打印一次,默认就是一步
print(list[::2])  # 这种效果和上面差不多,如果是从0开始,可以把0省略不写

 

函数:

12、len(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
len(list)    # 返回列表元素的个数
print(len(list))

10

 

13、max(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(max(list))# 返回列表元素的最大值

744

 

14、min(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(min(list))# 返回列表元素的最小值

744
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值