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

Introduction to Python Lists 列表介绍

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

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

相关推荐

Python字符串格式化:你真的会用吗?告别混乱代码,看这一篇就够

大家好!今天我们来聊聊Python中一个看似简单却暗藏玄机的操作——字符串格式化。你是不是还在用%s拼凑变量?或者写了无数个format()却依然被同事吐槽代码太“复古”?别急,这篇干货带你解锁三种神...

Python Unicode字符串编程实用教程

Unicode是现代文本处理的基础,本教程将介绍Python中的Unicode字符串处理,涵盖从基础概念到高级应用等。一、Unicode基础概念1.1Unicode与编码核心概念:Unicode:字...

殊途同归 python 第 6 节:字符串的使用

字符串作为Python的基础数据之一,以下是字符串的几种最常用情形,直接上代码1.声明字符串a="helloworld"b='竹杖芒鞋轻胜马,谁怕,一蓑烟雨任平生...

python爬虫字符串定位开始跟结束(find方法的使用)

python爬虫采集的时候会需要对采集的内容进行处理行为,处理什么?简单的说就是处理多余的HTML代码跟确定文章标题跟结尾,还有内容区间,方法如下:首先先是定位,我们先假设我们采集到了一批数据,数据里...

python 入门到脱坑 基本数据类型—字符串string

以下是Python字符串(String)的入门详解,包含基础操作、常用方法和实用技巧,适合初学者快速掌握:一、字符串基础1.定义字符串#单引号/双引号s1='hello's...

python字符串知识点总结

Python字符串知识点总结1.字符串基础字符串是不可变的序列类型可以用单引号(')、双引号(")或三引号('''或""")创建三引号...

在 Python 中使用 f-String 格式化字符串

在Python3.6中引入的f字符串提供了一种既简洁又可读的字符串格式新方法。f字符串的正式名称为格式化字符串文字,是以f或F为前缀的字符串,其中包含大括号内的表达式。这些表达式在...

零起点Python机器学习快速入门-4-3-字符串常用方法

Python中字符串的多种操作。包括去除字符串首尾的空格和特定字符、字符串的连接、查找字符在字符串中的位置、字符串之间的比较、计算字符串的长度、大小写转换以及字符串的分割。通过这些操作,我们可以对字...

Python 中 字符串处理的高效方法,不允许你还不知道

以下是Python中字符串处理的高效方法,涵盖常用操作、性能优化技巧和实际应用场景,帮助您写出更简洁、更快速的代码:一、基础高效操作1.字符串拼接:优先用join()代替+原因:join()预...

Python字符串详解与示例

艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...

Python中去除字符串末尾换行符的方法

技术背景在Python编程中,处理字符串时经常会遇到字符串末尾包含换行符的情况,如从文件中读取每一行内容时,换行符会作为字符串的一部分被读取进来。为了满足后续处理需求,需要将这些换行符去除。实现步骤1...

表格编程之争:Python VS VBA?Excel用户:新编程语言才真香!

Python和VBA哪个更好用?Python和VBA是两种不同的编程语言,它们都有自己的特点和优缺点。在表格编程方面,VBA在Excel中的应用非常广泛,可以通过宏来实现自动化操作和数据处理,也可以通...

用Python把表格做成web可视化图表

Python中有一个streamlit库,Streamlit的美妙之处在于您可以直接在Python中创建Web应用程序,而无需了解HTML、CSS或JavaScrip,今天我们就用st...

使用 Python 在 PowerPoint 演示文稿中创建或提取表格

PowerPoint中的表格是一种以结构化格式组织和呈现数据的方法,类似于Excel或Word等其他应用程序中表格的使用方式。它们提供了一种清晰简洁的方式来显示信息,使您的受众更容易消化和理...

用python实现打印表格的方法

最近在做表格输出的任务,一般有两种方法实现在控制台打印,一种是根据表格的输出规则自己写代码实现,另外一种是安装python的第三方依赖包prettytable实现这个效果。方法1:根据表格规则写代码...