博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python列表之修改、添加、删除、查询(四)
阅读量:7024 次
发布时间:2019-06-28

本文共 2191 字,大约阅读时间需要 7 分钟。

本篇讲列表的操作与维护

直接代码演示吧

1.讲字符串转换为列表

1 #列表的维护2 #将字符串转换为列表3 print(list("hello"))

输出结果

['h', 'e', 'l', 'l', 'o']

2.修改元素

1 #修改元素2 x = [1,2,3,4,5];3 x[1]=04 print(x)

输出结果

[1, 0, 3, 4, 5]

3.增加元素

#增加元素 append()names = ["a","b","c","d"]#append()仅支持添加一个元素names.append("e")#extend()增加一个列表names.extend(["e","f"])#insert()根据索引添加元素names.insert(1,"t")print(names)

输出结果

['a', 't', 'b', 'c', 'd', 'e', 'e', 'f']

4.删除

1 #删除remove()删除指定值的元素 2 x = [1,2,3,4,5] 3 x.remove(2) 4 print("--------删除2----------") 5 print(x) 6 names=["Alice","Linda","Bob"] 7 names.remove("Bob") 8 print("--------删除BOb----------") 9 print(names)10 11 #del 根据索引删除元素12 numbers = [6,7,8,9,10,11]13 del numbers[1]14 print("--------删除索引1----------")15 print(numbers)16 17 # pop()根据索引删除元素18 numbers1 = [6,7,8,9,10,11]19 numbers1.pop(1)20 print("--------删除索引1----------")21 print(numbers1)22 numbers1.pop()23 print("--------删除最后一个元素----")24 print(numbers1)

输出结果

--------删除2----------[1, 3, 4, 5]--------删除BOb----------['Alice', 'Linda']--------删除索引1----------[6, 8, 9, 10, 11]--------删除索引1----------[6, 8, 9, 10, 11]--------删除最后一个元素----[6, 8, 9, 10]

5.分片赋值

1 #分片赋值 2 str1 = ["a","b","c"] 3 # 替换索引>=2 4 str1[2:] = list("de") 5 print("替换索引>=2结果 :",str1) 6 #删除索引2 7 str1[2:2] = "f" 8 print("删除索引2结果 :",str1) 9 #赋值且替换索引2-310 str1[2:4] = ["g","h","i"]11 print("赋值且替换索引2-3结果 :",str1)12 #删除元素13 str1[:] = []14 print("删除所有结果 :",str1)

输出结果

替换索引>=2结果 : ['a', 'b', 'd', 'e']删除索引2结果 : ['a', 'b', 'f', 'd', 'e']赋值且替换索引2-3结果 : ['a', 'b', 'g', 'h', 'i', 'e']删除所有结果 : []

6.搜索元素

1 #搜索元素2 names1=["Alice","Linda","Bob"]3 if "Alice" in names1:4     print(True)5 else:6     print(False)

输出结果

True

7.搜索元素索引值

1 #index()元素索引值2 str1 = ["a","b","c"]3 print(str1.index("a"))

输出结果

0

8.统计元素出现次数

1 #count()统计某元素出现次数2 number1 = [1,2,1,3,4]3 print(number1.count(1))

输出结果

2

9.反向存放

1 #reverse将列表中的元素反向存放,返回值为null2 number1 = [1,2,1,3,4]3 number1.reverse();4 print(number1)

输出结果

[4, 3, 1, 2, 1]

 10.排序

1 #sort()方法:对元素进行排序,返回值为null2 number1 = [1,2,1,3,4]3 number1.sort()4 print(number1)5 #sorted()返回值为排序后的数组6 number2 = [1,2,1,3,4]7 y=sorted(number2);8 print(y)9 print(number2)

 输出结果

[1, 1, 2, 3, 4][1, 1, 2, 3, 4][1, 2, 1, 3, 4]

 

转载于:https://www.cnblogs.com/zhangyating/p/8127095.html

你可能感兴趣的文章
poj 1654 Area 求面积 水题 +longlong %lld输出
查看>>
POJ-3468 A Simple Problem with Integers Splay树
查看>>
【Windows】XShell中使用小键盘和ALT键(作Meta键),使BackSpace正常
查看>>
Preprocessor directives
查看>>
DOM 综合练习(二)
查看>>
php-redis的配置与使用
查看>>
mysql中(存储)函数
查看>>
Carthage 的使用
查看>>
linux系统盘扩容操作
查看>>
CDQ分治与整体二分学习笔记
查看>>
qt 常见问题记录
查看>>
Day24 中间件 自定义分页 ModelForm 序列化 缓存 信号
查看>>
codeforces 700A As Fast As Possible 二分求和?我觉得直接解更好
查看>>
POJ 2299 Ultra-QuickSort 求逆序数 线段树或树状数组 离散化
查看>>
让linux好用起来--操作使用技巧
查看>>
816:Abbott's Revenge
查看>>
JQuery选择器
查看>>
nmcli 使用记录---fatt
查看>>
【技巧】EasyUI分页组件pagination显示项控制
查看>>
POJ 3989 A hard Aoshu Problem
查看>>