Python数据结构(五)——排序和搜索

本文介绍了几种常见的排序和搜索算法,包括顺序查找、有序顺序查找、二分法查找、冒泡排序、选择排序和插入排序等,并提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

排序和搜索

15 in [3,3,2,1,4]
False
3 in [3,4,5,6]
True

顺序查找

# 查找列表中的项,假设列表项无序
def sequence_search(alist,item):
    pos = 0
    found = False
    while pos<len(alist) and not found:
        if alist[pos]==item:
            found = True
        else:
            pos += 1
    return found

testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(sequence_search(testlist, 3))
print(sequence_search(testlist, 13))        
False
True
# 查找列表中的项,假设列表项有序
def order_sequence_search(alist,item):
    pos = 0
    found = False
    stop = False
    while pos < len(alist) and not found and not stop:
        if alist[pos] == item:
            found = True
        else:
            if alist[pos]>item:
                stop = True
            else:
                pos += 1
    return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(order_sequence_search(testlist, 3))
print(order_sequence_search(testlist, 13))
False
True

二分法查找

def binary_search(alist,item):
    first = 0
    last = len(alist)-1
    found = False

    while first<=last and not found:
        mid = (first+last)/2
        if alist[mid]==item:
            found = True
        elif alist[mid]>item:
            last = mid - 1
        else:
            first = mid + 1
    return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))        
False
True
# 递归实现
def bianary_search(alist,item):
    if len(alist)==0:
        return False
    else:
        mid = len(alist)//2
        if alist[mid]==item:
            return True
        else:
            if item<alist[mid]:
                return bianary_search(alist[:mid],item)
            else:
                return bianary_search(alist[mid+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13)) 
False
True

Hash查找

哈希表 是以一种容易找到它们的方式存储的项的集合。哈希表的每个位置,通常称为一个槽,可以容纳一个项,并且由从 0 开始的整数值命名。例如,我们有一个名为 0 的槽,名为 1 的槽,名为 2 的槽,以上。最初,哈希表不包含项,因此每个槽都为空。我们可以通过使用列表来实现一个哈希表,每个元素初始化为None 。Figure 4 展示了大小 m = 11 的哈希表。换句话说,在表中有 m 个槽,命名为 0 到 10。

具体介绍见:Hash查找

def hash(astring, tablesize):
    sum = 0
    for pos in range(len(astring)):
        sum = sum+ord(astring[pos])
    return sum%tablesize

冲突解决:

排序

# 冒泡排序
def bubble_sort_1(alist):
    for j in range(len(alist)-1,0,-1):
        for i in range(j):
            if alist[i]>alist[i+1]:
                alist[i],alist[i+1]=alist[i+1],alist[i]
    return alist
alist = [54,26,93,17,77,31,44,55,20]
print bubble_sort_1(alist)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
# 优化冒泡排序,识别有序序列,修改冒泡排序提前停止
def bubble_sort_2(alist):
    exchange = True
    j = len(alist)-1
    while j>0 and exchange:
        exchange = False
        for i in range(j):
            if alist[i] > alist[i+1]:
                alist[i],alist[i+1]=alist[i+1],alist[i]
                exchange = True
        j -= 1
    return alist

alist=[30,20,40,90,50,60,70,80,100,110]
print bubble_sort_2(alist)
[20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
# 简单选择排序
def select_sort(alist):
    for i in range(len(alist)):
        k = i
        for j in range(k,len(alist)):
            if alist[k]>alist[j]:
                k = j
        alist[i],alist[k]=alist[k],alist[i]
    return alist
alist = [54,26,93,17,77,31,44,55,20]
print select_sort(alist)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
# 插入排序
def insert_sort(alist):
    for i in range(0,len(alist)):
        for j in range(i+1,len(alist)):
            if alist[i]>alist[j]:
                tmp = alist[j]
                alist.pop(j)
                alist.insert(i,tmp)
    return alist
alist = [54,26,93,17,77,31,44,55,20]
print insert_sort(alist)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
# 插入排序2
def insert_sort_2(A):
    length = len(A)
    if length < 2:
        return A

    for i in range(1,length-1):
        key = A[i]
        j = i-1
        while j>=0 and A[j]>key:
            A[j+1]=A[j]
            j -= 1
        A[j+1] = key
    return A
alist = [54,26,93,17,77,31,44,55,20]
print insert_sort_2(alist)
[17, 26, 31, 44, 54, 55, 77, 93, 20]

更多排序算法见博客:Python排序算法

### 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、付费专栏及课程。

余额充值