我试图在python中找到列表的前k个元素,而不使用heapq或对列表进行排序。
这就是我试过的,
list = [20,4,67,22,445,1,34]
k = 3
newList=[]
for i in range(0,k):
newList.append(list[i])
for i in list:
mini = min(newList)
if i <= mini:
continue
else:
newList.remove(mini)
newList.append(i)
print newList
但我得到67,67,445。我在这里做错了什么?
答案 0 :(得分:3)
添加一些跟踪时,问题很明显:
>>> list = [20,4,67,22,445,1,34]
>>> k = 3
>>> newList=[]
>>>
>>> for i in range(0,k):
... newList.append(list[i])
...
>>> for i in list:
... mini = min(newList)
... if i <= mini:
... continue
... else:
... print newList
... print "Replacing {0} with {1}".format(mini, i)
... newList.remove(mini)
... newList.append(i)
... print newList
... print '-' * 20
...
[20, 4, 67]
Replacing 4 with 20
[20, 67, 20]
--------------------
[20, 67, 20]
Replacing 20 with 67
[67, 20, 67]
--------------------
[67, 20, 67]
Replacing 20 with 22
[67, 67, 22]
--------------------
[67, 67, 22]
Replacing 22 with 445
[67, 67, 445]
当您对其进行迭代并再次添加时,您已经在列表中有67个。
我会把它重写为:
>>> numbers = [20,4,67,22,445,1,34]
>>> k = 3
>>> newList = numbers[:k]
>>>
>>> for i in numbers[k:]:
... mini = min(newList)
... if i > mini:
... print "Replacing {0} with {1}".format(mini, i)
... newList.remove(mini)
... newList.append(i)
...
Replacing 4 with 22
Replacing 20 with 445
Replacing 22 with 34
>>> print newList
[67, 445, 34]
但我不会将您的列表命名为list
。
答案 1 :(得分:1)
你可以简单地这样做:
a = [20,4,67,22,445,1,34]
k = 3
newList=[]
for i in range(k):
pos = a.index(max(a))
newList.append(a[pos])
a.pop(pos)
>>> print newList
[67, 445, 34]
答案 2 :(得分:0)
你的新名单中有67个,而67个从不弹出
答案 3 :(得分:0)
hughdbrown的解决方案有一个我注意到的错误。
如果列表具有类似的条目,则结果将仅显示这些条目之一。
例如,如果列表为[1, 2, 3, 4, 5, 5]
,则结果将显示[3, 4, 5]
而不是[4, 5, 5]