程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Introduction to Python Lists 列表介绍

hfteth 2025-05-09 18:54:54 技术文章 8 ℃

What is a List in Python?

In Python, a list is a versatile (多功能的) data structure that allows you to store a collection of items. It is mutable (可变的), which means you can change, add, or remove items after creating the list. Lists are defined using square brackets [] and items are separated by commas. They can hold different types of data, such as numbers, strings, and even other lists!

Create a List

You can create a list by putting items inside []. For example:

# A list of numbers
numbers = [1, 2, 3, 4, 5]

# A list of strings
fruits = ["apple", "banana", "cherry"]

# A mixed list (contains numbers, string, and a boolean)
mixed_list = [10, "hello", True]

# An empty list
empty_list = []

Access Items in a List

Items in a list have positions called indexes (索引). Python uses zero-based indexing, which means the first item is at index 0, the second at index 1, and so on. You can access an item by its index using square brackets.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

You can also use negative indexes to access items from the end. For example, -1 refers to the last item, -2 to the second last, etc.

print(fruits[-1])  # Output: cherry
print(fruits[-2])  # Output: banana

Change Items in a List

Since lists are mutable, you can change the value of an item by assigning a new value to its index.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"  # Change the second item to "orange"
print(fruits)  # Output: ["apple", "orange", "cherry"]

Add Items to a List

There are several ways to add items to a list:

  1. append(): Adds an item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # Output: ["apple", "banana", "cherry"]
  1. insert(): Adds an item at a specific index.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")  # Insert "banana" at index 1
print(fruits)  # Output: ["apple", "banana", "cherry"]

Remove Items from a List

You can remove items from a list using different methods:

  1. del keyword: Removes an item by index.
fruits = ["apple", "banana", "cherry"]
del fruits[1]  # Remove the item at index 1
print(fruits)  # Output: ["apple", "cherry"]
  1. remove(): Removes the first occurrence of a specific value.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # Output: ["apple", "cherry"]
  1. pop(): Removes and returns the item at a specific index (default is the last item).
fruits = ["apple", "banana", "cherry"]
popped_item = fruits.pop()  # Remove the last item
print(popped_item)  # Output: cherry
print(fruits)  # Output: ["apple", "banana"]

List Length

You can get the number of items in a list using the len() function.

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # Output: 3

List Operations

  • Concatenation (合并): You can combine two lists using the + operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]
  • Repetition (重复): You can repeat a list using the * operator.
list3 = ["a", "b"]
repeated_list = list3 * 3
print(repeated_list)  # Output: ["a", "b", "a", "b", "a", "b"]

Loop Through a List

You can use a for loop to iterate (遍历) through the items in a list.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

List Comprehension (列表推导式)

List comprehension is a concise way to create lists. It allows you to build a new list from an existing list in one line of code.

# Create a list of squared numbers
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Check if an Item Exists

You can use the in keyword to check if an item is present in a list.

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)  # Output: True
print("grape" in fruits)  # Output: False

Python列表介绍

什么是Python中的列表?

在Python中,列表(list)是一种多功能的数据结构,用于存储一组数据项。它是可变的(mutable),这意味着你可以在创建列表后修改、添加或删除其中的元素。列表用方括号[]定义,元素之间用逗号分隔。列表可以存储不同类型的数据,例如数字、字符串,甚至其他列表!

创建列表

你可以通过在[]中放入元素来创建列表。例如:

# 数字列表
numbers = [1, 2, 3, 4, 5]

# 字符串列表
fruits = ["apple", "banana", "cherry"]

# 混合列表(包含数字、字符串和布尔值)
mixed_list = [10, "hello", True]

# 空列表
empty_list = []

访问列表中的元素

列表中的元素有称为索引(indexes)的位置。Python使用从零开始的索引,即第一个元素位于索引0,第二个位于索引1,依此类推。你可以通过索引使用方括号访问元素。

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # 输出:apple
print(fruits[2])  # 输出:cherry

你也可以使用负索引从末尾访问元素。例如,-1表示最后一个元素,-2表示倒数第二个元素,等等。

print(fruits[-1])  # 输出:cherry
print(fruits[-2])  # 输出:banana

修改列表中的元素

由于列表是可变的,你可以通过为元素的索引赋值来修改其值。

fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"  # 将第二个元素改为"orange"
print(fruits)  # 输出:["apple", "orange", "cherry"]

向列表中添加元素

有几种向列表添加元素的方法:

  1. append():在列表末尾添加一个元素。
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # 输出:["apple", "banana", "cherry"]
  1. insert():在指定索引处添加一个元素。
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")  # 在索引1处插入"banana"
print(fruits)  # 输出:["apple", "banana", "cherry"]

从列表中删除元素

你可以使用不同方法从列表中删除元素:

  1. del关键字:通过索引删除元素。
fruits = ["apple", "banana", "cherry"]
del fruits[1]  # 删除索引1处的元素
print(fruits)  # 输出:["apple", "cherry"]
  1. remove():删除指定值的第一个匹配项。
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # 输出:["apple", "cherry"]
  1. pop():删除并返回指定索引处的元素(默认删除最后一个元素)。
fruits = ["apple", "banana", "cherry"]
popped_item = fruits.pop()  # 删除最后一个元素
print(popped_item)  # 输出:cherry
print(fruits)  # 输出:["apple", "banana"]

列表长度

你可以使用len()函数获取列表中元素的数量。

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 输出:3

列表运算

  • 合并(Concatenation):你可以使用+运算符合并两个列表。
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # 输出:[1, 2, 3, 4, 5, 6]
  • 重复(Repetition):你可以使用*运算符重复一个列表。
list3 = ["a", "b"]
repeated_list = list3 * 3
print(repeated_list)  # 输出:["a", "b", "a", "b", "a", "b"]

遍历列表

你可以使用for循环遍历列表中的元素。

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

输出:

apple
banana
cherry

列表推导式(List Comprehension)

列表推导式是创建列表的简洁方式,允许你用一行代码从现有列表生成新列表。

# 创建一个平方数列表
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)  # 输出:[1, 4, 9, 16, 25]

检查元素是否存在

你可以使用in关键字检查元素是否存在于列表中。

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)  # 输出:True
print("grape" in fruits)  # 输出:False

专业词汇和不常用词汇表

list, /lst/, 列表
mutable, /'mjutbl/, 可变的
indexes, /'ndsz/, 索引
zero-based indexing, /'zro best 'ndeks/, 从零开始的索引
append, /'pend/, 添加(到末尾)
insert, /n'srt/, 插入
remove, /r'muv/, 删除
pop, /pɑp/, 弹出(删除并返回)
len(), /len/, 长度(函数)
concatenation, /knkaet'nen/, 合并
repetition, /rep'tn/, 重复
iterate, /'tret/, 遍历
comprehension, /kɑmpr'henn/, 推导式

最近发表
标签列表