列表

列表在其他语言中通常叫做数组。

列表用 [] 定义,数据之间用 , 分隔。

列表的索引从 0 开始,索引又可以称为下标。

索引越界会报错。

列表中可以放置任意数据类型,也可以多种数据类型混着放。

程序示例:

list1 = []  # 创建一个空列表
list2 = list()  # 创建一个空列表
list3 = [10, 9.9, "hello", True]
print(list1)  # []
print(list2)  # []
print(list3)  # [10, 9.9, 'hello', True]
print(type(list1))  # <class 'list'>
print(type(list2))  # <class 'list'>
print(type(list3))  # <class 'list'>

程序示例:

list1 = list(range(1, 11))
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(type(list1))  # <class 'list'>
list2 = list("hello")
print(list2)  # ['h', 'e', 'l', 'l', 'o']
print(type(list2))  # <class 'list'>

程序示例:

list1 = list(range(1, 3))
print(list1)  # [1, 2]
list2 = list("hello")
print(list2)  # ['h', 'e', 'l', 'l', 'o']
print(list1 + list2)  # [1, 2, 'h', 'e', 'l', 'l', 'o']
print(list1 * 3)  # [1, 2, 1, 2, 1, 2]

程序示例:

print('1' in [1, 2, 3])  # False
print('2' not in [1, 2, 3])  # True
print(3 in [1, 2, 3])  # True

程序示例:

print([1, 2, 3, 4, 5] < [6, 7, 8, 9])  # True
print([3, 4, 5, 6, 7, 8, 9] < [1, 2, 3, 4, 5, 6, 7, 8, 9])  # False

程序示例:

print(len(list("hello")))  # 5
print(max(list("hello")))  # o
print(min(list("hello")))  # e

程序示例:

list1 = list(range(1, 11))
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del list1  # del 是一个关键字
# print(list1)  # 报错:NameError: name 'list1' is not defined. Did you mean: 'list'?

列表的遍历:

程序示例:

list1 = list(range(1, 11))
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in list1:
    print(i)

带着索引输出列表:

程序示例:

list1 = [1, 2, 3, 'a', 'b', 'c']
for i, j in enumerate(list1):
    print(i, j)

结果:

0 1
1 2
2 3
3 a
4 b
5 c

程序示例:

# append 方法:在列表末尾添加元素
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list.append("hello"))  # None
print(my_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello']

程序示例:

# extend 方法:在列表末尾添加列表
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list.extend(list("hello")))  # None
print(my_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 'h', 'e', 'l', 'l', 'o']

程序示例:

my_list = [1, 2, 3, 4, 5]
my_list.insert(2, "hello")
print(my_list)  # [1, 2, 'hello', 3, 4, 5]

程序示例:

# pop 方法根据索引删除元素,返回元素
my_list = [1, 2, 3, 4, 5]
print(my_list.pop(2))  # 3
print(my_list)  # [1, 2, 4, 5]

程序示例:

# remove 方法根据元素删除元素,不返回元素,有多个相同元素时,删除第一个
my_list = ['hello', 'world', 'hello', 'world']
print(my_list.remove('world'))  # None
print(my_list)  # ['hello', 'hello', 'world']

程序示例:

my_list = ['hello', 'world', 'hello', 'world']
my_list.clear()
print(my_list)  # []

程序示例:

# 计算评价年龄
ages = [33, 56, 42, 75, 12]
sum = 0
for age in ages:
    sum += age
print("平均年龄为 %d" % (sum / len(ages)))  # 平均年龄为 43

或者:

# 计算评价年龄
ages = [33, 56, 42, 75, 12]
print("平均年龄为 %d" % (sum(ages) / len(ages)))  # 平均年龄为 43
posted @ 2025-10-30 22:09  YouKong  阅读(1)  评论(0)    收藏  举报