如何将切片中的元素全部显示在由单个 space 分隔的一行上,并按从高到低的顺序排序

how do I display the elements in the slice all on one line separated by a single space and sorted in highest to lowest order

我应该在这个函数中定义一个名为 process 的函数 它需要将切片中的元素全部显示在一行中,由一个 space 分隔并按从高到低排序 order.And 我需要在过程函数中使用 for 循环。


def main():
    import random

    nums=[]

    for i in range(7):
        nums.append (random.randrange(20,80))
        result=nums

    while 20 <= result <=80:
        pass
    print result
    print ("The highest number is"),max(result)
    print ("The lowest number is"), min(result)

    #result.sort()
    print ("The middle 5 sorted high to low:")
    print (process (result))

def process(total):
    for num in total:
        result.sort()
        #print ("The middle 5 sorted high to low:")
    return result


main()

输出应如下所示

[67, 73, 24, 33, 70, 33, 47]
The highest number is 73
The lowest number is 24
The middle 5 sorted high to low:
[24, 33, 33, 47, 67]

下面呢。不使用循环,只是排序和切片。

def process(total):
    total.sort()
    return total[1:-1] #take all numbers except the first and the last

下面的代码应该可以工作。

我在你的代码中注意到的一些事情是过程函数调用结果,它没有在函数内部定义(你可能想阅读 Python 变量范围)。另外,while循环完全没用。

import random

def main():

    nums=[]

    for i in range(7):
        nums.append( random.randrange(20,80) )

    print nums
    print ("The highest number is"), max(nums)
    print ("The lowest number is"), min(nums)

    print ("The middle 5 sorted from high to low:")
    print ( sorted(nums)[1:-1] )

main()

这似乎是您想要完成的:

def main():
    import random

    nums=[]

    for i in range(7):
        nums.append (random.randrange(20,80))
        result=nums

    print (result)
    print ("The highest number is " ,max(result))
    print ("The lowest number is " , min(result))

    #result.sort()
    print ("The middle 5 sorted high to low:")
    process (result)

def process(total):
    dist_from_ends = (len(total) - 5) // 2
    slice_ = total[dist_from_ends:-dist_from_ends]

    for number in sorted(slice_):
        print(number, end=" ")
        # this only works in Python3

这导致输出:

[69, 57, 31, 60, 64, 64, 36]
The highest number is  69
The lowest number is  31
The middle 5 sorted high to low:
31 57 60 64 64