Day04_Python@lisongye - list列表
- ------------------------------START------------------------------
lsy_01 类:列表
可以放置任何东西的“集合",可以嵌套任何类型。
- 表示方式
li = [1,12.9,‘age’,[“李松野”,“lisongye”],‘lsy’,True]
列表用中括号括起来,每个元素之间使用逗号分割。 - 注意事项
列表中的元素可以是数字、字符串、列表、布尔值,所有东西都可以成为列表元素。
lsy_02 方法
-
在原值后边追加:append
li = [11,22,33]
li.append(66)
print(li)
[11, 22, 33, 66] -
清空列表:clear
li = [11,22,33]
li.clear()
print(li)
[] -
浅拷贝:copy
li = [11,22,33]
v = li.copy()
print(v)
[11, 22, 33] -
计算出现的次数:count
li = [11,22,22,33]
v = li.count(22)
print(v) -
扩展原列表:extend(参数:可迭代对象)
li = [11,22,22,33]
li.extend([55,22,11])
print(li)
[11, 22, 22, 33, 55, 22, 11]
注意:
extand和append的区别:
li = [11,22,22,33]
li.append([55,22,11])
print(li)
[11, 22, 22, 33, [55, 22, 11]] -
根据值获取当前值索引位置(左边优先):index
li = [11,22,22,33]
n = li.index(33)
print(n)
3 -
在指定索引位置插入元素:insert
li = [11,22,22,33]
li.insert(2,11)
print(li)
[11, 22, 11, 22, 33] -
删除某个索引位置的值,并获取删除的值:pop
li = [11,22,22,33]
n = li.pop(1) #默认删除最后一个值并获取
print(n)
22 -
删除指定值:remove(优先左侧)
li = [11,22,22,33]
li.remove(22)
print(li)
[11, 22, 33] -
将当前列表翻转:reverse
li = [11,22,22,33]
li.reverse()
print(li)
[33, 22, 22, 11] -
列表排序:sort(默认升序)
li = [11,44,22,55,33]
li.sort()
print(li)
[11, 22, 33, 44, 55]
–
li = [11,44,22,55,33]
li.sort(reverse=True) #降序
print(li)
[55, 44, 33, 22, 11]
lsy_03 其他功能
-
索引取值:
li = [11,44,22,55,33]
print(li[3])
print(li[1:3])
55
[44, 22] -
for、while循环都可使用:
li = [11,44,22,55,33]
for i in li:
print(i)
11
44
22
55
33 -
索引修改列表元素:
li = [11,44,22,55,33]
li[0] = 00
print(li)
[0, 44, 22, 55, 33]
字符串生成后不可修改,但列表可修改。 -
切片修改列表元素:
li = [11,44,22,55,33]
li[3:5] = [44,55]
print(li)
[11, 44, 22, 44, 55] -
in操作:
li = [11,44,22,55,33]
n = 11 in li
print(n) -
str转换为list
a = ‘lisongye’
n = list(a)
print(n)
[‘l’, ‘i’, ‘s’, ‘o’, ‘n’, ‘g’, ‘y’, ‘e’] -
list转换为str
a = ‘lisongye’
n = list(a)
print(n)
[‘l’, ‘i’, ‘s’, ‘o’, ‘n’, ‘g’, ‘y’, ‘e’] -
str转换为:list
a = [‘l’, ‘i’, ‘s’, ‘o’, ‘n’, ‘g’, ‘y’, ‘e’]
n =’’
for i in a:
n += str(i)
print(n)
在没有数字的情况下,也可以:
a = [‘l’, ‘i’, ‘s’, ‘o’, ‘n’, ‘g’, ‘y’, ‘e’]
n = ‘’.join(a)
print(n)
- E-mail:lisongye@126.com
- WeChat:baobeilsy
- Copyright © lisongye All Rights Reserved
- ------------------------------END------------------------------