截屏2020-12-24 下午6.34.35.png

一、列表

(1)作用

可以存储多个,任意数据类型的数据,多个数据有顺序的。(存钱罐)
用逗号区分元素
**
songs = [1,
2,
3,
“月亮之上”]

(2)type()、len()

print(len(songs))
print(type(songs))

输出:
4

(3)索引和切片

索引返回元素数据类型,超出范围会报错
切片返回列表,超出范围不报错
**
songs = [1,
2,
3,
“月亮之上”]
print(songs[3])
# print(songs[999]) #IndexError: list index out of range
print(songs[2:])

输出:
月亮之上
[3, ‘月亮之上’]


(4)list的修改操作

1、增加

songs = [1, 2, 3, “月亮之上”]

# 1 添加一个元素
songs.append(“love_story”) # 用得多 ->python内部都是用’’表示字符串

# 2 添加多个元素,列表合并
songs.extend([“告白气球”, “歌曲1”]) # 用不多

# 3 选择添加的位置
songs.insert(2, “告白气球222”) #
指定位置添加print(songs)**

输出:
[1, 2, ‘告白气球222’, 3, ‘月亮之上’, ‘love_story’, ‘告白气球’, ‘歌曲1’]

2、删除

songs = [1, 2, 3, “月亮之上”]

1 全部删除 选择索引删除 选择元素删除
**
songs.clear() #清空列表元素
输出:
[]

2 根据值删除,要删除的元素
**
songs.remove(“月亮之上”)
输出:
[1, 2, 3]

3 根据索引删除 ,数据可以找回来
**
songs.pop(1)
输出:
[1, 3, ‘月亮之上’]

4 del #不要用 从内存中删除,数据找不回来
del songs[0]
print(songs)
输出:
[]

3、修改

# 修改索引为0的元素
songs[0] = “夜曲”
print(songs)

输出:
[‘夜曲’, 2, 3, ‘月亮之上’]

4、查找

1 索引和切片

2 count() 统计次数

songs = [1, 2, 3, “月亮之上”]

print(songs.count(“月亮之上”))
输出:
1

3 index() 获取索引。用于列表的查找,找不到值会报错(ValueError: substring not found

print(songs.index(“月亮之上”))
输出:
3

4 字符串的 find() 和 index() 区别:find查找不到返回-1,index找不到值会报错
print(“hello”.find(“l”))
print(“hello”.index(“l”))

(5)排序

对数字进行排序

1、sort() 正序

num = [1, 222, 31, 34, 55]
num.sort()
print(num)
输出:
[1, 31, 34, 55, 222]

2、reverse() 反序

num = [1, 222, 31, 34, 55]
num.reverse()
print(num)
输出:
[55, 34, 31, 222, 1]

3、降序

结合使用sort()和reverse()
num = [1, 222, 31, 34, 55]
num.sort()
num.reverse()

print(num)
输出:
[222, 55, 34, 31, 1]
3、

二、元组

(1)type()、len()

songs = (1, 2)
print(type(songs))
print(len(songs))

输出:

2

(2) 空的元组

songs = ()
print(type(songs))
print(len(songs))

输出:

0

(3) 单个元素的元组

一个元素需要写逗号 ,不然元组不生效
**
songs = (“夜曲”,)
print(type(songs))
print(len(songs))

输出:

1

(4)元素不可编辑

不可变类型
只能查询 :索引和切片,index ,count
songs = (1, 2)
print(songs[0])
print(songs[0:])
print(songs.index(2))
print(songs.count(2))

输出:
1
(1, 2)
1
1