python 内置数据结构的基本操作 —— list(2)

本文详细介绍了Python中列表的各种方法,包括添加、删除、排序等操作,并通过实例展示了这些方法的具体用法。

The list data type has some more methods. Here are all of the methods of list objects:

list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.clear()
Remove all items from the list. Equivalent to del a[:].

list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.count(x)
Return the number of times x appears in the list.

list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()
Reverse the elements of the list in place.

list.copy()
Return a shallow copy of the list. Equivalent to a[:].

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

Thedel statement
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del can also be used to delete entire variables:

>>> del a
### Python 中的数据排序方法 在 Python 中,可以通过内置函数 `sorted()` 或列表对象的 `.sort()` 方法实现数据排序。以下是两种方式的具体介绍: #### 使用 `sorted()` 函数 `sorted()` 是一个内置函数,能够返回一个新的已排序列表,不会修改原始数据结构。其语法如下: ```python sorted(iterable, key=None, reverse=False) ``` - **iterable**: 可迭代的对象(如列表、元组等)。 - **key**: 自定义排序逻辑的函数,默认为 None。 - **reverse**: 排序方向,默认为 False 表示升序;如果设置为 True,则按降序排列。 示例代码: ```python data = [3, 1, 4, 1, 5, 9] result = sorted(data) # 升序排序 print(result) # 输出: [1, 1, 3, 4, 5, 9] result_desc = sorted(data, reverse=True) # 降序排序 print(result_desc) # 输出: [9, 5, 4, 3, 1, 1] ``` #### 使用 `.sort()` 方法 `.sort()` 是列表的一个原地排序方法,会直接修改原有列表的内容而不创建新列表。它的参数与 `sorted()` 类似: ```python list.sort(key=None, reverse=False) ``` 示例代码: ```python data = [3, 1, 4, 1, 5, 9] data.sort() # 升序排序 print(data) # 输出: [1, 1, 3, 4, 5, 9] data.sort(reverse=True) # 降序排序 print(data) # 输出: [9, 5, 4, 3, 1, 1] ``` #### 高级排序技巧:自定义键函数 当需要按照特定规则排序时,可以使用 `key` 参数指定一个函数来决定排序依据。例如,对于复杂数据类型的排序,可借助 `operator.itemgetter()` 提高效率[^1]。 示例代码: ```python from operator import itemgetter data = [('apple', 2), ('banana', 1), ('cherry', 3)] # 按照第二个元素排序 result = sorted(data, key=itemgetter(1)) print(result) # 输出: [('banana', 1), ('apple', 2), ('cherry', 3)] # 对字典中的值进行排序 dict_data = {'a': 3, 'b': 1, 'c': 2} result_dict = dict(sorted(dict_data.items(), key=lambda x: x[1])) print(result_dict) # 输出: {'b': 1, 'c': 2, 'a': 3} ``` #### Pandas 数据框中的排序 在数据分析场景下,通常会用到 Pandas 库对 DataFrame 进行排序。Pandas 的 `DataFrame.sort_values()` 和 `DataFrame.sort_index()` 方法提供了灵活的支持[^4]。 示例代码: ```python import pandas as pd df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 22], 'score': [88, 95, 78] }) # 按某一列排序 sorted_df = df.sort_values(by='age') print(sorted_df) # 多列联合排序 multi_sorted_df = df.sort_values(by=['age', 'score'], ascending=[True, False]) print(multi_sorted_df) ``` --- ### 总结 Python 提供了多种方式进行数据排序,无论是简单的一维数组还是复杂的多维度表格数据,都能找到合适的工具完成任务。熟练掌握这些方法有助于提高开发效率并简化代码逻辑。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值