
列表是可以具有不同数据类型的项的有序集合。列表是可变的,这意味着它们的内容可以在创建后更改。
创建列表可以通过将项目放在方括号内来创建列表 [] ,用逗号分隔。
# 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']List 方法列表有几个内置方法,允许我们对它们执行操作。
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.pop()print(last_fruit) # Output: orangeprint(fruits) # Output: ['apple', 'blueberry', 'cherry']# Reversing the listfruits.reverse()print(fruits) # Output: ['cherry', 'blueberry', 'apple']# Sorting the listfruits.sort()print(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'Tuple 方法元组只有两个内置方法:
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何时使用列表和元组列表:当您需要可修改的项目集合时,请使用列表。列表适用于需要添加、删除或更改项目的场景。元组:当需要不应修改的项的集合时,请使用元组。元组非常适合存储常量或固定的项集合。