简介
字符串和元组是不可变的,而列表是可变(mutable)的,可以对它进行随意修改。
一.定义列表
# TODO 定义一个列表
a = [1, 2, 3]
print(a)
# TODO 字符串转为列表
b = 'qwe'
print(list(b))
# TODO 将元组转为列表
c = (4, 5, 6)
print(list(c))
# [1, 2, 3]
# ['q', 'w', 'e']
# [4, 5, 6]
二.索引index
index 方法用于从列表中找出某个元素的位置,如果有多个相同的元素,则返回第一个元素的位置
x = ['hello', 'world', 'you', 'me', 'me']
print(x.index('you'))
print(x.index('me'))
# 2
# 3
三.统计元素count
统计某个元素在列表中出现的次数
x = ['hello', 'world', 'you', 'me', 'me']
print(x.count('you'))
print(x.count('me'))
print(x.count('123'))
# 1
# 2
# 0
四.追加元素append
在列表末尾增加新的元素
x = ['hello', 'world', 'you', 'me', 'me']
x.append('test')
x.append(1)
x.append([3, 4])
x.append((5, 6))
x.append({"1": "2"})
print(x)
# ['hello', 'world', 'you', 'me', 'me', 'test', 1, [3, 4], (5, 6), {'1': '2'}]
五.合并列表extend
1.将一个新列表的元素添加到原列表中,虽然 append 和 extend 可接收一个列表作为参数
2.但是 append 方法是将其作为一个元素添加到列表中,而 extend 则是将新列表的元素逐个添加到原列表中。
x = ['hello', 'world']
y = ['you', 'me', 'me']
print(x + y)
x.extend(y)
print(x)
print(y)
# ['hello', 'world', 'you', 'me', 'me']
# ['hello', 'world', 'you', 'me', 'me']
# ['you', 'me', 'me']
六.插入元素
将某个元素添加到某个位置
x = ['hello', 'world']
x.insert(1, '123')
print(x)
# ['hello', '123', 'world']
七.根据索引移除元素pop
移除列表中的一个元素(默认是最后一个),并且返回该元素的值
x = ['hello', 'world', "123", "456"]
y = [1, 2, 3, 4]
x.pop(1)
y.pop()
print(x)
print(y)
# ['hello', '123', '456']
# [1, 2, 3]
八.移除指定元素remove
用于移除列表中的某个匹配元素,如果有多个匹配,则移除第一个
x = ['hello', "123", 'world', "123"]
y = ['hello', 'world', "123"]
x.remove('123')
y.remove('hello')
print(x)
print(y)
# ['hello', 'world', '123']
# ['world', '123']
九.反转列表reverse
x = ['hello', "123", 'world', "123"]
x.reverse()
print(x)
# ['123', 'world', '123', 'hello']
十.排序sort/sorted
sort用于对列表进行排序,注意该方法会改变原来的列表,而不是返回新的排序列表
sorted用于返回一个排序后的新列表
x = [1, 3, 5, 2, 2, 3, 5, 6, 8]
y = [6, 4, 78, 9, 2]
x.sort()
z = sorted(y)
print(x)
print(y)
print(z)
# [1, 2, 2, 3, 3, 5, 5, 6, 8]
# [6, 4, 78, 9, 2]
# [2, 4, 6, 9, 78]
不管是 sort 方法还是 sorted 函数,默认排序都是升序排序。reverse 关键字参数进行设置排序方式
x = [1, 3, 5, 2, 2, 3, 5, 6, 8]
y = [3, 4, 2, 7, 9, 5]
x.sort(reverse=True)
z = sorted(y, reverse=True)
print(x)
print(z)
# [8, 6, 5, 5, 3, 3, 2, 2, 1]
# [9, 7, 5, 4, 3, 2]
除了 reverse 关键字参数,还可以指定 key 关键字参数,它为每个元素创建一个键,
然后所有元素按照这个键来排序,比如我们想根据元素的长度来排序
x = ['a', 'ccc', 'bb', '2', 'ddddddd', 'fffff']
x.sort(key=len)
print(x)
# ['a', '2', 'bb', 'ccc', 'fffff', 'ddddddd']
多列(属性)排序
students = [
('john', 'B', 15),
('jane', 'A', 12),
('dave', 'B', 10),
('ethan', 'C', 20),
('peter', 'B', 20),
('mike', 'C', 16)
]
# TODO 对第 3 列排序 (从小到大)
print(sorted(students, key=lambda student: student[2]))
# TODO 对第 2 列排序(从小到大),再对第 3 列从大到小排序
print(sorted(students, key=lambda student: (student[1], -student[2])))
# TODO lambda函数需要进一步学习
# [('dave', 'B', 10), ('jane', 'A', 12), ('john', 'B', 15), ('mike', 'C', 16), ('ethan', 'C', 20), ('peter', 'B', 20)]
# [('jane', 'A', 12), ('peter', 'B', 20), ('john', 'B', 15), ('dave', 'B', 10), ('ethan', 'C', 20), ('mike', 'C', 16)]