如何在Python中查找列表中的第1,第2,第3最高值

时间:2020-12-28 13:12:47

I know how to find the 1st highest value but don't know the rest. Keep in mind i need to print the position of the 1st 2nd and 3rd highest value.Thank You and try to keep it simple as i have only been coding for 2 months. Also they can be joint ranks

我知道如何找到第一个最高值,但不知道其余的值。请记住,我需要打印第一个第二和第三个最高值的位置。谢谢你,并尽量保持简单,因为我只编码了2个月。他们也可以成为联合队伍

def linearSearch(Fscore_list):
    pos_list = []
    target = (max(Fscore_list))
    for i in range(len(Fscore_list)):
        if Fscore_list[i] >= target:
            pos_list.append(i)


        return pos_list

8 个解决方案

#1


3  

This will print a list of the 3 highest items, each paired with its index:

这将打印3个最高项目的列表,每个项目与其索引配对:

lst = [9,7,43,2,4,7,8,5,4]
print( sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )[:3] )

Things are a bit more complicated if the same value can appear multiple times (this will show the highest position for a value):

如果相同的值可以出现多次(这将显示值的最高位置),事情会更复杂一些:

lst = [9,7,43,2,4,7,8,5,4]
ranks = sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )
values = []
posns = []
for x,i in ranks:
    if x not in values:
        values.append( x )
        posns.append( i )
        if len(values) == 3:
            break
print zip( values, posns )

#2


2  

Use heapq.nlargest:

>>> import heapq
>>> [i
...     for x, i
...     in heapq.nlargest(
...         3,
...         ((x, i) for i, x in enumerate((0,5,8,7,2,4,3,9,1))))]
[7, 2, 3]

#3


1  

Add all the values in the list to a set. This will ensure you have each value only once.

将列表中的所有值添加到集合中。这将确保您只有一次值。

Sort the set.

对集合进行排序。

Find the index of the top three values in the set in the original list.

找到原始列表中集合中前三个值的索引。

Make sense?

Edit

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)

print('1st = ' + str(theset[0]) + ' at ' + str(thelist.index(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thelist.index(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thelist.index(theset[2])))

Edit

You still haven't told us how to handle 'joint winners' but looking at your responses to other answers I am guessing this might possibly be what you are trying to do, maybe? If this is not the output you want please give us an example of the output you are hoping to get.

你还没有告诉我们如何处理'联合赢家',但看着你对其他答案的回答我猜这可能是你想要做的,也许?如果这不是您想要的输出,请给我们一个您希望获得的输出示例。

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)
thedict = {}
for j in range(3):
    positions = [i for i, x in enumerate(thelist) if x == theset[j]]
    thedict[theset[j]] = positions

print('1st = ' + str(theset[0]) + ' at ' + str(thedict.get(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thedict.get(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thedict.get(theset[2])))

Output

1st = 103 at [8, 9]
2nd = 88 at [2, 5]
3rd = 45 at [1, 4]

BTW : What if all the values are the same (equal first) or for some other reason there is no third place? (or second place?). Do you need to protect against that? If you do then I'm sure you can work out appropriate safety shields to add to the code.

顺便说一句:如果所有的值都相同(等于第一个)或者出于其他原因没有第三个位置怎么办? (或第二名?)。你需要保护吗?如果你这样做,我相信你可以找到合适的安全防护罩来添加到代码中。

#4


0  

There's a complicated O(n) algorithm, but the simplest way is to sort it, which is O(n * log n), then take the top. The trickiest part here is to sort the data while keeping the indices information.

有一个复杂的O(n)算法,但最简单的方法是对它进行排序,即O(n * log n),然后取顶部。这里最棘手的部分是在保持索引信息的同时对数据进行排序。

from operator import itemgetter

def find_top_n_indices(data, top=3):
    indexed = enumerate(data)  # create pairs [(0, v1), (1, v2)...]
    sorted_data = sorted(indexed, 
                         key=itemgetter(1),   # sort pairs by value 
                         reversed=True)       # in reversed order
    return [d[0] for d in sorted_data[:top]]  # take first N indices

data = [5, 3, 6, 3, 7, 8, 2, 7, 9, 1]
print find_top_n_indices(data)  # should be [8, 5, 4]

Similarly, it can be done with heapq.nlargest(), but still you need to pack the initial data into tuples and unpack afterwards.

类似地,它可以使用heapq.nlargest()来完成,但是您仍然需要将初始数据打包到元组中并在之后解压缩。

#5


0  

To have a list filtered and returned in descending order with duplicates removed try using this function. You can pass in how many descending values you want it to return as keyword argument.

要删除列表并按降序返回并删除重复项,请尝试使用此函数。您可以传递要将其作为关键字参数返回的降序值。

Also a side note, if the keyword argument (ordered_nums_to_return) is greater than the length of the list, it will return the whole list in descending order. if you need it to raise an exception, you can add a check to the function. If no args is passed it will return the highest value, again you can change this behaviour if you need.

另外注意,如果关键字参数(ordered_nums_to_return)大于列表的长度,它将按降序返回整个列表。如果需要它来引发异常,可以在函数中添加一个检查。如果没有传递args,它将返回最高值,如果需要,您可以再次更改此行为。

list_of_nums = [2, 4, 23, 7, 4, 1]


def find_highest_values(list_to_search, ordered_nums_to_return=None):
    if ordered_nums_to_return:
        return sorted(set(list_to_search), reverse=True)[0:ordered_nums_to_return]
    return [sorted(list_to_search, reverse=True)[0]]

print find_highest_values(list_of_nums, ordered_nums_to_return=4)

#6


0  

If values can appear in your list repeatedly you can try this solution.

如果值可以重复显示在列表中,则可以尝试此解决方案。

def search(Fscore_list, num=3):
    l = Fscore_list
    res = dict([(v, []) for v in sorted(set(l), reverse=True)[:num]])
    for index, val in enumerate(l):
        if val in res:
            res[val].append(index)
    return sorted(res.items(), key=lambda x: x[0], reverse=True)

First it find num=3 highest values and create dict with empty list for indexes for it. Next it goes over the list and for every of the highest values (val in res) save it's indexes. Then just return sorted list of tuples like [(highest_1, [indexes ...]), ..]. e.g.

首先,它找到num = 3个最高值,并为其创建带有空列表的dict。接下来,它遍历列表,并且对于每个最高值(res中的val)保存它的索引。然后返回像[(highest_1,[index ...]),..]这样的元组的排序列表。例如

>>> l = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4]
>>> print(search(l))
[(43, [2, 6]), (9, [0]), (8, [7, 9])]

To print the positions do something like:

要打印位置,请执行以下操作:

>>> Fscore_list = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4, 43, 43, 43]
>>> result = search(Fscore_list)
>>> print("1st. %d on positions %s" % (result[0][0], result[0][1]))
1st. 43 on positions [2, 6, 11, 12, 13]
>>> print("2nd. %d on positions %s" % (result[1][0], result[1][1]))
2nd. 9 on positions [0]
>>> print("3rd. %d on positions %s" % (result[2][0], result[2][1]))
3rd. 8 on positions [7, 9]

#7


-1  

None is always considered smaller than any number.

没有人总是认为小于任何数字。

>>> None<4
True
>>> None>4
False

Find the highest element, and its index. Replace it by None. Find the new highest element, and its index. This would be the second highest in the original list. Replace it by None. Find the new highest element, which is actually the third one.

找到最高元素及其索引。将其替换为无。找到新的最高元素及其索引。这将是原始列表中的第二高。将其替换为无。找到新的最高元素,实际上是第三个元素。

Optional: restore the found elements to the list.

可选:将找到的元素恢复到列表中。

This is O(number of highest elements * list size), so it scales poorly if your "three" grows, but right now it's O(3n).

这是O(最高元素的数量*列表大小),因此如果你的“三”增长它会缩小,但现在它是O(3n)。

#8


-1  

Start by sorting the list into descending order:

首先将列表按降序排序:

my_list = [1, 2, 8, 4, 7, 6, 5, 3]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)

Output:

[8, 7, 6, 5, 4, 3, 2, 1]

You can then extract the index of the three largest elements (the first 3 elements of the sorted_list) as follows:

然后,您可以提取三个最大元素的索引(sorted_list的前3个元素),如下所示:

index_of_highest = my_list.index(sorted_list[0])
index_of_second_highest = my_list.index(sorted_list[1])
index_of_third_highest = my_list.index(sorted_list[2])

#1


3  

This will print a list of the 3 highest items, each paired with its index:

这将打印3个最高项目的列表,每个项目与其索引配对:

lst = [9,7,43,2,4,7,8,5,4]
print( sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )[:3] )

Things are a bit more complicated if the same value can appear multiple times (this will show the highest position for a value):

如果相同的值可以出现多次(这将显示值的最高位置),事情会更复杂一些:

lst = [9,7,43,2,4,7,8,5,4]
ranks = sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )
values = []
posns = []
for x,i in ranks:
    if x not in values:
        values.append( x )
        posns.append( i )
        if len(values) == 3:
            break
print zip( values, posns )

#2


2  

Use heapq.nlargest:

>>> import heapq
>>> [i
...     for x, i
...     in heapq.nlargest(
...         3,
...         ((x, i) for i, x in enumerate((0,5,8,7,2,4,3,9,1))))]
[7, 2, 3]

#3


1  

Add all the values in the list to a set. This will ensure you have each value only once.

将列表中的所有值添加到集合中。这将确保您只有一次值。

Sort the set.

对集合进行排序。

Find the index of the top three values in the set in the original list.

找到原始列表中集合中前三个值的索引。

Make sense?

Edit

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)

print('1st = ' + str(theset[0]) + ' at ' + str(thelist.index(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thelist.index(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thelist.index(theset[2])))

Edit

You still haven't told us how to handle 'joint winners' but looking at your responses to other answers I am guessing this might possibly be what you are trying to do, maybe? If this is not the output you want please give us an example of the output you are hoping to get.

你还没有告诉我们如何处理'联合赢家',但看着你对其他答案的回答我猜这可能是你想要做的,也许?如果这不是您想要的输出,请给我们一个您希望获得的输出示例。

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)
thedict = {}
for j in range(3):
    positions = [i for i, x in enumerate(thelist) if x == theset[j]]
    thedict[theset[j]] = positions

print('1st = ' + str(theset[0]) + ' at ' + str(thedict.get(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thedict.get(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thedict.get(theset[2])))

Output

1st = 103 at [8, 9]
2nd = 88 at [2, 5]
3rd = 45 at [1, 4]

BTW : What if all the values are the same (equal first) or for some other reason there is no third place? (or second place?). Do you need to protect against that? If you do then I'm sure you can work out appropriate safety shields to add to the code.

顺便说一句:如果所有的值都相同(等于第一个)或者出于其他原因没有第三个位置怎么办? (或第二名?)。你需要保护吗?如果你这样做,我相信你可以找到合适的安全防护罩来添加到代码中。

#4


0  

There's a complicated O(n) algorithm, but the simplest way is to sort it, which is O(n * log n), then take the top. The trickiest part here is to sort the data while keeping the indices information.

有一个复杂的O(n)算法,但最简单的方法是对它进行排序,即O(n * log n),然后取顶部。这里最棘手的部分是在保持索引信息的同时对数据进行排序。

from operator import itemgetter

def find_top_n_indices(data, top=3):
    indexed = enumerate(data)  # create pairs [(0, v1), (1, v2)...]
    sorted_data = sorted(indexed, 
                         key=itemgetter(1),   # sort pairs by value 
                         reversed=True)       # in reversed order
    return [d[0] for d in sorted_data[:top]]  # take first N indices

data = [5, 3, 6, 3, 7, 8, 2, 7, 9, 1]
print find_top_n_indices(data)  # should be [8, 5, 4]

Similarly, it can be done with heapq.nlargest(), but still you need to pack the initial data into tuples and unpack afterwards.

类似地,它可以使用heapq.nlargest()来完成,但是您仍然需要将初始数据打包到元组中并在之后解压缩。

#5


0  

To have a list filtered and returned in descending order with duplicates removed try using this function. You can pass in how many descending values you want it to return as keyword argument.

要删除列表并按降序返回并删除重复项,请尝试使用此函数。您可以传递要将其作为关键字参数返回的降序值。

Also a side note, if the keyword argument (ordered_nums_to_return) is greater than the length of the list, it will return the whole list in descending order. if you need it to raise an exception, you can add a check to the function. If no args is passed it will return the highest value, again you can change this behaviour if you need.

另外注意,如果关键字参数(ordered_nums_to_return)大于列表的长度,它将按降序返回整个列表。如果需要它来引发异常,可以在函数中添加一个检查。如果没有传递args,它将返回最高值,如果需要,您可以再次更改此行为。

list_of_nums = [2, 4, 23, 7, 4, 1]


def find_highest_values(list_to_search, ordered_nums_to_return=None):
    if ordered_nums_to_return:
        return sorted(set(list_to_search), reverse=True)[0:ordered_nums_to_return]
    return [sorted(list_to_search, reverse=True)[0]]

print find_highest_values(list_of_nums, ordered_nums_to_return=4)

#6


0  

If values can appear in your list repeatedly you can try this solution.

如果值可以重复显示在列表中,则可以尝试此解决方案。

def search(Fscore_list, num=3):
    l = Fscore_list
    res = dict([(v, []) for v in sorted(set(l), reverse=True)[:num]])
    for index, val in enumerate(l):
        if val in res:
            res[val].append(index)
    return sorted(res.items(), key=lambda x: x[0], reverse=True)

First it find num=3 highest values and create dict with empty list for indexes for it. Next it goes over the list and for every of the highest values (val in res) save it's indexes. Then just return sorted list of tuples like [(highest_1, [indexes ...]), ..]. e.g.

首先,它找到num = 3个最高值,并为其创建带有空列表的dict。接下来,它遍历列表,并且对于每个最高值(res中的val)保存它的索引。然后返回像[(highest_1,[index ...]),..]这样的元组的排序列表。例如

>>> l = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4]
>>> print(search(l))
[(43, [2, 6]), (9, [0]), (8, [7, 9])]

To print the positions do something like:

要打印位置,请执行以下操作:

>>> Fscore_list = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4, 43, 43, 43]
>>> result = search(Fscore_list)
>>> print("1st. %d on positions %s" % (result[0][0], result[0][1]))
1st. 43 on positions [2, 6, 11, 12, 13]
>>> print("2nd. %d on positions %s" % (result[1][0], result[1][1]))
2nd. 9 on positions [0]
>>> print("3rd. %d on positions %s" % (result[2][0], result[2][1]))
3rd. 8 on positions [7, 9]

#7


-1  

None is always considered smaller than any number.

没有人总是认为小于任何数字。

>>> None<4
True
>>> None>4
False

Find the highest element, and its index. Replace it by None. Find the new highest element, and its index. This would be the second highest in the original list. Replace it by None. Find the new highest element, which is actually the third one.

找到最高元素及其索引。将其替换为无。找到新的最高元素及其索引。这将是原始列表中的第二高。将其替换为无。找到新的最高元素,实际上是第三个元素。

Optional: restore the found elements to the list.

可选:将找到的元素恢复到列表中。

This is O(number of highest elements * list size), so it scales poorly if your "three" grows, but right now it's O(3n).

这是O(最高元素的数量*列表大小),因此如果你的“三”增长它会缩小,但现在它是O(3n)。

#8


-1  

Start by sorting the list into descending order:

首先将列表按降序排序:

my_list = [1, 2, 8, 4, 7, 6, 5, 3]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)

Output:

[8, 7, 6, 5, 4, 3, 2, 1]

You can then extract the index of the three largest elements (the first 3 elements of the sorted_list) as follows:

然后,您可以提取三个最大元素的索引(sorted_list的前3个元素),如下所示:

index_of_highest = my_list.index(sorted_list[0])
index_of_second_highest = my_list.index(sorted_list[1])
index_of_third_highest = my_list.index(sorted_list[2])

相关文章