17

如果我有一个每次长度都不同的列表,并且我想将它从最低到最高排序,我会怎么做?

如果我有:[-5, -23, 5, 0, 23, -6, 23, 67]

我想:[-23, -6, -5, 0, 5, 23, 23, 67]

我从这个开始:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]

new_list = []

minimum = data_list[0]  # arbitrary number in list 

for x in data_list: 
  if x < minimum:
    minimum = value
    new_list.append(i)

但是这只经历了一次,我得到:

new_list = [-23] 

这就是我卡住的地方。

如何len(new_list) = len(data_list)在不使用内置最大、最小、排序函数的情况下继续循环直到(即所有数字都在新列表中)对所有内容进行排序?我也不确定是否有必要创建一个新列表。

4

24 回答 24

43

我猜你正在尝试做这样的事情:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # arbitrary number in list 
    for x in data_list: 
        if x < minimum:
            minimum = x
    new_list.append(minimum)
    data_list.remove(minimum)    

print new_list
于 2012-08-15T05:34:54.560 回答
15
l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]

for i in range(len(l)):
    for j in range(i + 1, len(l)):

        if l[i] > l[j]:
           l[i], l[j] = l[j], l[i]

print l

输出:

[1, 2, 3, 11, 12, 22, 23, 25, 34, 44, 64, 122]
于 2018-03-29T18:15:26.797 回答
5

这是我一直在尝试的东西。(插入排序-不是最好的排序方式,但确实有效)

def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        i = index-1
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break
于 2014-09-13T18:13:50.003 回答
4

这严格遵循您不使用sort(),的要求min()max()但也通过不重新发明轮子来使用 Python 最佳实践。

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
import heapq
heapq.heapify(data_list)
new_list = []
while data_list:
    new_list.append(heapq.heappop(data_list)))

我建议查看 Python 库heapq.py以了解它是如何工作的。Heapsort 是一种非常有趣的排序算法,因为它可以让您“排序”一个无限的流,即您可以快速获取当前最小的项目,还可以有效地将新项目添加到要排序的数据中。

于 2012-08-15T08:10:24.887 回答
2

这行得通!

def sorting(li):
    for i in range(len(li)):
        for j in range(len(li)):
            if li[i] < li[j]:
                li[j],li[i] = li[i],li[j]
    return li

listToSort = [22,11,23,1,100,24,3,101,2,4]
print(sorting(listToSort))
于 2020-10-10T07:42:50.810 回答
1
def bubble_sort(seq):
    """Inefficiently sort the mutable sequence (list) in place.
       seq MUST BE A MUTABLE SEQUENCE.

       As with list.sort() and random.shuffle this does NOT return 
    """
    changed = True
    while changed:
        changed = False
        for i in xrange(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return None

if __name__ == "__main__":
   """Sample usage and simple test suite"""

   from random import shuffle

   testset = range(100)
   testcase = testset[:] # make a copy
   shuffle(testcase)
   assert testcase != testset  # we've shuffled it
   bubble_sort(testcase)
   assert testcase == testset  # we've unshuffled it back into a copy

来自: http ://rosettacode.org/wiki/Bubble_Sort#Python

于 2012-08-15T05:20:41.183 回答
1

这是一个不是很有效的排序算法:)

>>> data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
>>> from itertools import permutations
>>> for p in permutations(data_list):
...     if all(i<=j for i,j in zip(p,p[1:])):
...         print p
...         break
... 
(-23, -6, -5, 0, 5, 23, 23, 67)
于 2012-08-15T05:29:15.360 回答
1

尝试排序列表,char 有 ascii 码,同样可以用于排序 char 列表。

aw=[1,2,2,1,1,3,5,342,345,56,2,35,436,6,576,54,76,47,658,8758,87,878]
for i in range(aw.__len__()):
    for j in range(aw.__len__()):
        if aw[i] < aw[j] :aw[i],aw[j]=aw[j],aw[i]
于 2017-08-08T12:37:26.817 回答
1
data = [3, 1, 5, 2, 4]
n = len(data)
    for i in range(n):
        for j in range(1,n):
            if data[j-1] > data[j]:
                (data[j-1], data[j]) = (data[j], data[j-1])
    print(data)
于 2019-03-29T05:03:15.283 回答
1
# Your current setup
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list  = []

# Sort function
for i in data_list:
    new_list = [ x for x in new_list if i > x ] + [i] + [ x for x in new_list if i <= x ]
于 2019-07-10T20:24:09.153 回答
0

我的方法——

s = [-5, -23, 5, 0, 23, -6, 23, 67]
nl = []
for i in range(len(s)):
    a = min(s)
    nl.append(a)
    s.remove(a)

print nl
于 2015-09-12T22:25:26.407 回答
0

解决方案

mylist = [1, 6, 7, 8, 1, 10, 15, 9]
print(mylist)
n = len(mylist)
for i in range(n):
    for j in range(1, n-i):
        if mylist[j-1] > mylist[j]:
             (mylist[j-1], mylist[j]) = (mylist[j], mylist[j-1])
print(mylist)
于 2015-10-06T02:59:55.207 回答
0

这是一个更易读的就地 插入排序算法示例。

a = [3, 1, 5, 2, 4]

for i in a[1:]:
    j = a.index(i)
    while j > 0 and a[j-1] > a[j]:
        a[j], a[j-1] = a[j-1], a[j]
        j = j - 1
于 2016-09-08T21:33:40.557 回答
0
def my_sort(lst):
    a = []
    for i in range(len(lst)):
        a.append(min(lst))
        lst.remove(min(lst))
    return a

def my_revers_sort(lst):#in revers!!!!!
    a = []
    for i in range(len(lst)):
        a.append(max(lst))
        lst.remove(max(lst))
    return a
于 2016-09-18T12:48:54.177 回答
0

您可以使用 min() 函数轻松完成

`def asc(a):
    b=[]
    l=len(a)
    for i in range(l):
        x=min(a)
        b.append(x)
        a.remove(x)
    return b
 print asc([2,5,8,7,44,54,23])`
于 2018-09-07T18:57:01.803 回答
0
n = int(input("Input list lenght: "))
lista = []
for i in range (1,n+1):
    print ("A[",i,"]=")
    ele = int(input())
    lista.append(ele)
print("The list is: ",lista)
invers = True
while invers == True:
    invers = False 
    for i in range (n-1):
        if lista[i]>lista[i+1]:
            c=lista[i+1]
            lista[i+1]=lista[i]
            lista[i]=c
            invers = True
print("The sorted list is: ",lista)
于 2019-10-16T11:03:30.200 回答
0

将值从第一个位置交换到列表的末尾,此代码循环 (n*n-1)/2 次。每次它从零索引开始将较大的值推送到较大的索引。

list2 = [40,-5,10,2,0,-4,-10]
for l in range(len(list2)):
    for k in range(l+1,len(list2)):
        if list2[k] < list2[l]:
            list2[k] , list2[l] = list2[l], list2[k]
print(list2)
于 2019-12-12T17:31:40.210 回答
0

由于复杂性无关紧要,我向您介绍... BogoSort:

from random import shuffle

def is_sorted(ls):
    for idx in range(len(ls)-1):
        if x[idx] > x[idx + 1]:
          return False
    return True

def sort(ls):
    while not is_sorted(ls):
        shuffle(ls)
    return ls


ls = list(range(5))
shuffle(ls)

print(
    "Original: ",
    ls
)

print(
    "Sorted: ",
    sorted(ls)
)
于 2020-10-10T08:08:17.667 回答
0

这是未排序的列表,我们想要的是 1234567

list = [3,1,2,5,4,7,6]

def sort(list):
    for i in range(len(list)-1):
        if list[i] > list[i+1]:
            a = list[i]
            list[i] = list[i+1]
            list[i+1] = a
        print(list)       

sort(list)

以最简单的方法对数组进行排序。我正在使用当前的冒泡排序,即:它检查前 2 个位置并将最小的数字向左移动,依此类推。“-n”in loop是为了避免缩进错误,这样做你就会明白。

于 2021-01-21T20:06:18.070 回答
0

您可以使用迭代方法与递归函数一一进行比较。如果要降序,则按升序排列结果,然后将条件从更改if l[i]>l[i+1]if l[i]<l[i+1]

l=[2,1,3,4,3,2,1,2] 
list_len=len(l)

def fun(l):
    for i in range(list_len):
        if i<list_len-1:
            if l[i]>l[i+1]:
                l[i],l[i+1]=l[i+1],l[i]
                fun(l)
    return l
            
print(fun(l))
于 2021-06-20T16:40:16.017 回答
0
for i in range (0, len(unsorted_list)):
    for j in range (i,  len(unsorted_list)):
        if unsorted_list[i]> unsorted_list[j]:
            unsorted_list[i], unsorted_list[j] = unsorted_list[j], unsorted_list[i]

print("Sorted list: ", unsorted_list)

输出为: 排序列表:[0, 5, 9, 10, 11, 20, 100, 100]

时间复杂度是二次时间 - O (n^2)

于 2021-10-21T12:12:33.260 回答
0

将此与 for 循环一起使用

    arr = [1, 5, 0, 0, 9, 10, 9, 3, 2, 3, 5,10]
    new_arr = []
    for index in range(len(arr)):
        index = len(new_arr) - index
        max_val = arr[index]
        for val in arr[index+1:]:
            if val >= max_val:
                max_val = val
        new_arr.append(max_val)
        arr.remove(max_val)
    print(new_arr)

将此与 while 循环一起使用

    arr = [1, 5, 0, 0, 9, 10, 9, 3, 2, 3, 5,10]
    new_arr = []
    while arr:
        max_val = arr[0]
        for x in arr:
            if x >= max_val:
                max_val = x
        new_arr.append(max_val)
        arr.remove(max_val)
    
    print(new_arr)

有功能,对于 ASC 使用 reverse = 1 和 -1 用于 DESC

    def custom_sorting(numbers, new_list, reverse=-1):
        for i in range(len(numbers)):
            first_num = numbers[0]
            for num in numbers:
                if num < first_num and reverse < 0:
                    first_num = num
                if num > first_num and reverse > 0:
                    first_num = num
    
            numbers.remove(first_num)
            new_list.append(first_num)
    
    
    if __name__ == "__main__":
        data = [5, 4, 2, 8, 70, 0, 0, 96, 5]
        newlist = []
        custom_sorting(data, newlist, reverse=1)
        print(newlist)```
于 2022-01-03T15:47:27.980 回答
-1

我如何继续循环直到 len(new_list) = len(data_list)

while len(new_list) != len(data_list):
    # ...

也许像这样?

不,没有必要创建一个新列表;大多数排序算法通过更改列表来工作。

您可能会尝试使用单独的列表进行选择排序。有关该排序算法的更多信息,请参阅 Wikipedia 文章,您将了解它如何与单个列表一起工作,以及它的效率如何(剧透:它不是)。

于 2012-08-15T05:22:02.037 回答
-3
def getIndexOfMaximum(list1):
    index = 0
    emptyList = []
    value = list1[0]
    c = 0
    while (c == 0):
        for cell in list1:
            index += 1
            if (cell >= value):
                value = cell
                hold = index -1
            if (len(list1) == index):
                emptyList += [value]
                del list1[hold]
                index = 0
                value = 0
                if (len(list1) == 1):
                    newList = emptyList + list1
                    del list1[index]
                    c = 1
    return newList
print(getIndexOfMaximum([2,5,8,7,44,54,23]))

#TRY THIS!!!
于 2016-11-01T20:55:47.657 回答