python学习-17 列表list 2
程序员文章站
2022-05-26 14:28:24
运行结果: #2. 字符串转换列表 运行结果: #3. 列表转换字符串 第一种方法:(for循环) 运算结果: 第二种方法:(列表中的元素只有字符串时) 运行结果: #4. list 的其他功能 -追加(也可以加字符串,列表等) 运算结果: -清空 运算结果: -浅拷贝 运算结果: -计数 运算结果 ......
# 1. 选择嵌套列表里的元素(内部进行了for循环)
li = [1,2,"age",["熊红","你好",["12",45]],"abc",true] a = li[3][2][1] print(a)
运行结果:
45 process finished with exit code 0
#2. 字符串转换列表
a = "iamchinese" b =list(a) print(b)
运行结果:
['i', 'a', 'm', 'c', 'h', 'i', 'n', 'e', 's', 'e'] process finished with exit code 0
#3. 列表转换字符串
第一种方法:(for循环)
li =[123,456,"abcdefg"] b = " " for a in li: b=b+str(a) print(b)
运算结果:
123456abcdefg process finished with exit code 0
第二种方法:(列表中的元素只有字符串时)
li =["abcdefg"] a ="".join(li) print(a)
运行结果:
abcdefg process finished with exit code 0
#4. list 的其他功能
-追加(也可以加字符串,列表等)
li = [123,13121,55] li.append(6) print(li)
运算结果:
[123, 13121, 55, 6] process finished with exit code 0
-清空
li = [123,13121,55] li.clear() print(li)
运算结果:
[] process finished with exit code 0
-浅拷贝
li = [123,13121,55] a = li.copy() print(li) print(a)
运算结果:
[123, 13121, 55] [123, 13121, 55] process finished with exit code 0
-计数
li = [55,123,13121,55] a =li.count(55) #计算 55 出现过几次 print(a)
运算结果:
2 process finished with exit code 0
-迭加
li = [1,2,3,4,5] li.extend([7,8,9,"你好"]) print(li)
运算结果:
[1, 2, 3, 4, 5, 7, 8, 9, '你好'] process finished with exit code 0
ps: append 将整个元素添加, extend 是内部经过for循环将一个添加
-获取位置
li = [1,22,33,4,5,33]
a=li.index(33) #(从左向右获取索引位置(获取到第一个就不会继续了),可以指定位置li.index(0:3)) print(a)
运算结果:
2 #(索引,不是数量) process finished with exit code 0
-删除某个元素并获取删除的元素
li = [1,22,33,4,5,33] a=li.pop() # 可以指定索引位置(不指定索引,默认删除最后一个) print(li) print(a)
运算结果:
[1, 22, 33, 4, 5] 33 process finished with exit code 0
-删除指定元素
li = [1,22,33,4,5,33] li.remove(33) #从左向右只删除第一个 print(li)
运算结果:
[1, 22, 4, 5, 33] process finished with exit code 0
-反转
li = [1,22,33,4,5,33] li.reverse() print(li)
运算结果:
[33, 5, 4, 33, 22, 1] process finished with exit code 0
-排序
li = [1,22,33,4,5,33] li.sort(reverse=true) # 括号里不填默认从小到大排序 print(li)
运算结果:
[33, 33, 22, 5, 4, 1] process finished with exit code 0
下一篇: 紫薯米怎么煮,一起来看看