» Python快速入门 » 2. 集合篇 » 2.1 列表

列表

构建列表

a = [1, 2, 3]
b = list("lite") # ['l', 'i', 't', 'e']

获取元素

a = ["Lite", 1, 3.14, False]
print(a[2]) # 3.14

更新元素

a = ["Lite", 1, 3.14]
a[1] = "Rank"
print(a) # ['Lite', 'Rank', 3.14]

常用方法

append 添加

a = [1, 2]
a.append(3)
print(a) # [1, 2, 3]

clear 清空

a = [1, 2]
a.clear()
print(a) # []

copy 拷贝

a = [1, 2]
b = a.copy()
print(b) # [1, 2]

extend 拓展

a = [1, 2]
b = [3, 4]
a.extend(b)
print(a) # [1, 2, 3, 4]

insert 插入

a = ["apple", "banana", "cherry"]
a.insert(1, "grape")
print(a) # ['apple', 'grape', 'banana', 'cherry']

reverse 逆转

a = [3, 9, 27, 78]
a.reverse()
print(a) # [78, 27, 9, 3]

sort 排序

a = ["banana", "grape", "cherry", "apple"]
a.sort()
print(a) # ['apple', 'banana', 'cherry', 'grape']

代码挑战

修改编辑器中代码,根据列表中各元素的长度排序。 如果两元素长度相同,根据二者字典序排序。

Loading...
> 此处输出代码运行结果
上页
下页