百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Introduction to Python Lists 列表介绍

itomcoil 2025-05-27 14:52 14 浏览

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/, 推导式

相关推荐

最强聚类模型,层次聚类 !!_层次聚类的优缺点

哈喽,我是小白~咱们今天聊聊层次聚类,这种聚类方法在后面的使用,也是非常频繁的~首先,聚类很好理解,聚类(Clustering)就是把一堆“东西”自动分组。这些“东西”可以是人、...

python决策树用于分类和回归问题实际应用案例

决策树(DecisionTrees)通过树状结构进行决策,在每个节点上根据特征进行分支。用于分类和回归问题。实际应用案例:预测一个顾客是否会流失。决策树是一种基于树状结构的机器学习算法,用于解决分类...

Python教程(四十五):推荐系统-个性化推荐算法

今日目标o理解推荐系统的基本概念和类型o掌握协同过滤算法(用户和物品)o学会基于内容的推荐方法o了解矩阵分解和深度学习推荐o掌握推荐系统评估和优化技术推荐系统概述推荐系统是信息过滤系统,用于...

简单学Python——NumPy库7——排序和去重

NumPy数组排序主要用sort方法,sort方法只能将数值按升充排列(可以用[::-1]的切片方式实现降序排序),并且不改变原数组。例如:importnumpyasnpa=np.array(...

PyTorch实战:TorchVision目标检测模型微调完

PyTorch实战:TorchVision目标检测模型微调完整教程一、什么是微调(Finetuning)?微调(Finetuning)是指在已经预训练好的模型基础上,使用自己的数据对模型进行进一步训练...

C4.5算法解释_简述c4.5算法的基本思想

C4.5算法是ID3算法的改进版,它在特征选择上采用了信息增益比来解决ID3算法对取值较多的特征有偏好的问题。C4.5算法也是一种用于决策树构建的算法,它同样基于信息熵的概念。C4.5算法的步骤如下:...

Python中的数据聚类及可视化分析实践

探索如何通过聚类分析揭露糖尿病预测数据集的特征!我们将运用Python的强力工具,深入挖掘数据,以直观的可视化揭示不同特征间的关系。一同探索聚类分析在糖尿病预测中的实践!所有这些可视化都可以通过数据操...

用Python来统计大乐透号码的概率分布

用Python来统计大乐透号码的概率分布,可以按照以下步骤进行:导入所需的库:使用Python中的numpy库生成数字序列,使用matplotlib库生成概率分布图。读取大乐透历史数据:从网络上找到大...

python:支持向量机监督学习算法用于二分类和多分类问题示例

监督学习-支持向量机(SVM)支持向量机(SupportVectorMachine,简称SVM)是一种常用的监督学习算法,用于解决分类和回归问题。SVM的目标是找到一个最优的超平面,将不同类别的...

25个例子学会Pandas Groupby 操作

groupby是Pandas在数据分析中最常用的函数之一。它用于根据给定列中的不同值对数据点(即行)进行分组,分组后的数据可以计算生成组的聚合值。如果我们有一个包含汽车品牌和价格信息的数据集,那么可以...

数据挖掘流程_数据挖掘流程主要有哪些步骤

数据挖掘流程1.了解需求,确认目标说一下几点思考方法:做什么?目的是什么?目标是什么?为什么要做?有什么价值和意义?如何去做?完整解决方案是什么?2.获取数据pandas读取数据pd.read.c...

使用Python寻找图像最常见的颜色_python 以图找图

如果我们知道图像或对象最常见的是哪种颜色,那么可以解决图像处理中的几个用例,例如在农业领域,我们可能需要确定水果的成熟度。我们可以简单地检查一下水果的颜色是否在预定的范围内,看看它是成熟的,腐烂的,还...

财务预算分析全网最佳实践:从每月分析到每天分析

原文链接如下:「链接」掌握本文的方法,你就掌握了企业预算精细化分析的能力,全网首发。数据模拟稍微有点问题,不要在意数据细节,先看下最终效果。在编制财务预算或业务预算的过程中,通常预算的所有数据都是按月...

常用数据工具去重方法_数据去重公式

在数据处理中,去除重复数据是确保数据质量和分析准确性的关键步骤。特别是在处理多列数据时,保留唯一值组合能够有效清理数据集,避免冗余信息对分析结果的干扰。不同的工具和编程语言提供了多种方法来实现多列去重...

Python教程(四十):PyTorch深度学习-动态计算图

今日目标o理解PyTorch的基本概念和动态计算图o掌握PyTorch张量操作和自动求导o学会构建神经网络模型o了解PyTorch的高级特性o掌握模型训练和部署PyTorch概述PyTorc...