面向初学者的 Python(数据结构:Python 中的列表和元组)

360影视 2025-02-03 07:57 2

摘要:# Creating a listfruits = ["apple", "banana", "cherry"]numbers = [1, 2, 3, 4, 5]mixed = ["apple", 2, 3.5, True]print(fruits) # Out

列表是可以具有不同数据类型的项的有序集合。列表是可变的,这意味着它们的内容可以在创建后更改。

可以通过将项目放在方括号内来创建列表 ,用逗号分隔。

# Creating a listfruits = ["apple", "banana", "cherry"]numbers = [1, 2, 3, 4, 5]mixed = ["apple", 2, 3.5, True]print(fruits) # Output: ['apple', 'banana', 'cherry']

使用列表项的索引进行访问,从 0 开始。

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

由于列表是可变的,因此可以更改其项。

fruits = ["apple", "banana", "cherry"]fruits[1] = "blueberry"print(fruits) # Output: ['apple', 'blueberry', 'cherry']

列表有几个内置方法,允许我们对它们执行操作。

fruits = ["apple", "banana", "cherry"]# Adding an item to the endfruits.append("orange")print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']# Inserting an item at a specific positionfruits.insert(1, "blueberry")print(fruits) # Output: ['apple', 'blueberry', 'banana', 'cherry', 'orange']# Removing an itemfruits.remove("banana")print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']# Popping the last itemlast_fruit = fruits.popprint(last_fruit) # Output: orangeprint(fruits) # Output: ['apple', 'blueberry', 'cherry']# Reversing the listfruits.reverseprint(fruits) # Output: ['cherry', 'blueberry', 'apple']# Sorting the listfruits.sortprint(fruits) # Output: ['apple', 'blueberry', 'cherry']

元组类似于列表,但它是不可变的,这意味着其内容在创建后无法更改。元组是通过将项目放在括号内来定义 的。

可以通过将项目放在括号内(用逗号分隔)来创建元组。

# Creating a tuplefruits = ("apple", "banana", "cherry")numbers = (1, 2, 3, 4, 5)mixed = ("apple", 2, 3.5, True)print(fruits) # Output: ('apple', 'banana', 'cherry')

元组项使用其索引进行访问,就像列表一样。

fruits = ("apple", "banana", "cherry")print(fruits[0]) # Output: appleprint(fruits[1]) # Output: bananaprint(fruits[2]) # Output: cherry元组的不变性

创建元组后,无法更改其内容。这意味着您不能添加、删除或修改元组中的项。

fruits = ("apple", "banana", "cherry")# The following operations will result in errors# fruits[1] = "blueberry" # TypeError: 'tuple' object does not support item assignment# fruits.append("orange") # AttributeError: 'tuple' object has no attribute 'append'# fruits.remove("banana") # AttributeError: 'tuple' object has no attribute 'remove'

元组只有两个内置方法:

fruits = ("apple", "banana", "cherry")# counting occurrences of an itemprint(fruits.count("banana")) # Output: 1# Finding the index of an itemprint(fruits.index("cherry")) # Output: 2

来源:自由坦荡的湖泊AI

相关推荐