替换列表中的重复项的排列

发布于 2025-01-28 03:44:05 字数 486 浏览 2 评论 0原文

假设我们有一个列表,我们想生成列表的排名,最小的值是结果列表中的1。说列表是[4,4,3],其中包含重复。因此,当重复发生重复时,我们将用重复元素的排列替换重复的元素。

在这种情况下,重复元素为2。

因此,结果应为[[3,2,1],[2,3,1]。

我目前通过反复找到最大元素来实现幼稚的实现:

def naive(lst):
    size = len(lst)
    rst = [None] * size
    for i in range(size):
        max_elt = max(lst)
        max_index = lst.index(max_elt)
        rst[max_index] = size-i
        lst[max_index] = 0
    return rst

这返回一个结果[3,2,1]。

另外,如果列表包含多个重复,例如[2,2,4,4]怎么办?

Let's say we have a list, and we want to generate a ranking of the list, with the smallest value being 1 in the resulting list. Say the list is [4,4,3], which contains duplicates. So, when duplicates occur, we will replace the repeated elements with the permutation of the repeated elements.

In this case, the repeated element is 2.

So, the result should be [[3,2,1],[2,3,1].

I currently have a naive implementation by repeatedly finding the largest element:

def naive(lst):
    size = len(lst)
    rst = [None] * size
    for i in range(size):
        max_elt = max(lst)
        max_index = lst.index(max_elt)
        rst[max_index] = size-i
        lst[max_index] = 0
    return rst

This returns a single result [3, 2, 1].

Also, what if the list contains multiple duplications, e.g. [2,2,4,4]?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文