python - 连接列表和 int

标签 python list sorting quicksort

我现在正在尝试学习 python,并且遇到了快速排序算法。这是我到目前为止用示例列表编写的内容: [3,1,2,2,1,3,6,7,5,4,8]

def quick(self):
    first = self.lst[0]
    l1 = []
    l2 = []
    for item in self.lst[1:]:
        if item <= first:
            l1.append(item)
            print('this is l1:',l1)
        else:
            l2.append(item)
            print('this is l2:', l2)

        return _____

我正在尝试执行 self.lst = l1 + first + l2,但是当我这样做时我收到一条错误消息:

self.lst = l1 + first + l2
builtins.TypeError: can only concatenate list (not "int") to list

我只是想使第一遍正确,并可能实现 while True until l1 = [] 或其他东西。

  1. 如何将 l1、first 和 l2 连接在一起?
  2. 你们建议我在第一步之后做什么?

非常感谢!

最佳答案

first 是一个 intl1l2 是列表,所以如果你用 [] 包含单个项目 (first) 然后你可以连接三个列表

self.lst = l1 + [first] + l2

numerous quicksort algorithms但是如果我们使用例如 Lomuto partition scheme维基百科上的伪代码实现是

algorithm quicksort(A, lo, hi) is
    if lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p - 1)
        quicksort(A, p + 1, hi)

algorithm partition(A, lo, hi) is
    pivot := A[hi]
    i := lo        // place for swapping
    for j := lo to hi - 1 do
        if A[j] ≤ pivot then
            swap A[i] with A[j]
            i := i + 1
    swap A[i] with A[hi]
    return i

在 Python 中这看起来像

def quicksort(A, lo, hi):
    if lo < hi:
        p = partition(A, lo, hi)
        quicksort(A, lo, p-1)
        quicksort(A, p+1, hi)

def partition(A, lo, hi):
    pivot = A[hi]
    i = lo
    for j in range(lo, hi):
        if A[j] <= pivot:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[i], A[hi] = A[hi], A[i]
    return i

测试这个实现

>>> lst = [3,1,2,2,1,3,6,7,5,4,8]
>>> quicksort(lst, 0, len(lst)-1)
>>> lst
[1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8]

关于python - 连接列表和 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496082/

相关文章:

python - 如何在 Python 包中安全地 "fake"模块

python - 在 Python 3 中使用\b

java - 如何将列表 <Products> 插入数据库

Javascript 排序数组 - 在比较函数内调用函数

javascript - 为什么 Chrome 中的排序行为不同?

python - 从 pandas Dataframe 中的混合 dtype 列中删除破折号字符串

python - 类装饰器禁用 __init_subclass__

python - 如何从列表列表中获取整数

python - 如果我在迭代列表时从列表中删除,为什么会跳过元素?

javascript - 对 javascript 数组进行排序,其中数字存储为文本