python列表中的多个最大数字

时间:2017-05-17 19:20:12

标签: python

import random as rd

ListNumbers1 = []
List1 = []


for j in range(1000):
    ListNumbers1 = rd.randint(1,10000)

我如何从ListNumbers1获得50个最高数字并附加到list1?

6 个答案:

答案 0 :(得分:2)

这样的东西?

List1.extend(sorted(ListNumbers1)[-50:])

答案 1 :(得分:2)

您在循环中反复分配相同的值,在此过程中销毁列表。使用append ...

更好:创建数字列表理解,然后使用heapq.nlargest直接获得50个最高数字:

import random as rd
import heapq

highest_50 = heapq.nlargest(50,[rd.randint(1,10000) for _ in range(1000)])

print(highest_50)

结果:

[9994, 9983, 9983, 9968, 9934, 9925, 9913, 9912, 9909, 9909, 9902, 9889, 9884, 9880, 9811, 9794, 9793, 9792, 9765, 9756, 9750, 9748, 9738, 9737, 9709, 9707, 9704, 9700, 9691, 9686, 9635, 9618, 9617, 9605, 9604, 9593, 9586, 9584, 9573, 9569, 9569, 9557, 9531, 9528, 9522, 9438, 9438, 9431, 9402, 9400]

答案 2 :(得分:1)

为了好玩,我有一个更有效的解决方案:

from random import randint
import heapq

# create a list of 1000 random numbers
# take the negative, so the min heap does what we want
dataset = [-randint(1, 10000) for _ in range(1000)]

# O(n) function to impose the heap invariant
heapq.heapify(dataset)

# sorting is O(n log n)
# extracting from a heap is log n per item
# therefore taking the 50 biggest is much more efficent if
# we use a heap to extract only the ones we need
top50 = [-heapq.heappop(dataset) for _ in range(50)]

print top50

这是一个更快的解决方案,因为您要提取的50远小于1000总输入大小。我重命名了变量,但这仅仅是我个人的偏好。

答案 3 :(得分:0)

就像那样(注意如何分配随机数):

import random as rd

ListNumbers1 = []
List1 = []


for j in range(1000):
    ListNumbers1.append(rd.randint(1,10000)) # fix: append each random element

ListNumbers1.sort()         # sort the list, ascending order
List1 = ListNumbers1[-50:]  # get last 50 elements of the list and assign it to List1

答案 4 :(得分:0)

import random as rd
List1 = sorted([rd.randint(1,10000) for j in range(1000)])[-50:]

切片排序列表理解的最后50个元素,然后你不需要ListNumbers1

答案 5 :(得分:0)

要搜索列表中的n个最大数字,您需要两个程序:一个用于查找最大值,另一个用于提取n个最大值。 您也可以对列表进行排序并先取n,但这不是我的方法,因为我需要保留原始列表并按原样进行研究。例如,您还可以知道每个所选数字的偏移量,这在某些情况下可能很有用。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
def n_biggest(lis,howmany):

    #this function returns the biggest of a list with its offset
    def biggest_in_list(lis):
        n=0
        biggest=0
        offset=0
        for item in lis:
            n=n+1
            if (item>biggest):
                biggest=item
                offset=n-1
        return[biggest,offset]

    #now this is the part where we create the descending list
    image=lis#the use of an image will prevent finding twice the same number
    result_list=[]
    if len(lis)<howmany:#this will prevent errors if list is too small
        howmany=len(lis)
    for i in range(howmany):
        find1=biggest_in_list(image)
        result_list.append(find1[0])
        image.pop(find1[1])
    return result_list

print n_biggest([5,4,6,10,233,422],3)#this line was for testing the above

希望这有帮助, 的问候,