1

我有一个这样的数字列表:

[687, 687, 683, 683, 677, 662....] 

它按降序排列,有很多数字。

我想表示它,列表中的数字越大,我想给它最小值等等。就像 687 变成 0,然后 683 变成 1,然后 677 变成 2,依此类推。

有没有办法做到这一点?

编辑:

实际上,我想将 new_list 表示为[0,0,4,4,10,25..]最高元素为 0,然后下一个元素是原始列表中的两个数字 + new_list 中的前一个数字的差,就像我们通过做得到 4(687-683) + 0等等。怎么做?

4

2 回答 2

4

从列表中创建一个Counter,替换排序结果的键,然后将其转回列表:

from collections import Counter
from itertools import count

# Get counts of each element in the list
original_counter = Counter([687, 687, 683, 683, 677, 662])

# Get only the unique values, in descending order
values = (v for k, v in sorted(original_counter.items(), reverse=True))

# Create a new counter out of 0, 1, 2, … and the sorted, unique values
new_counter = Counter(dict(zip(count(), values)))

# Retrieve a sorted list from the new counter
new_list = sorted(new_counter.elements())

print(new_list) # [0, 0, 1, 1, 2, 3]

这也不需要对原始列表进行排序。它实现了一个紧凑的功能:

from collections import Counter
from itertools import count

def enumerate_unique(iterable):
    return sorted(Counter(dict(zip(count(),
        (v for k, v in sorted(Counter(iterable).items(), reverse=True)))))
        .elements())

不过,再想一想,直截了当的方法还不错。它也更有效率。

def enumerate_unique(iterable):
    seen = {}
    counter = 0

    for x in iterable:
        i = seen.get(x)

        if i is None:
            seen[x] = counter
            yield counter
            counter += 1
        else:
            yield i

那个适用于任何列表。但是,由于您有一个排序列表,因此有一个非常好的 O(n):

def enumerate_unique(sorted_iterable):
    last = None
    counter = -1

    for x in sorted_iterable:
        if x != last:
            counter += 1

        yield counter

要按照描述跳过数字,您可以这样做:

def enumerate_unique(sorted_iterable):
    last = None
    last_index = -1

    for i, x in enumerate(sorted_iterable):
        if x != last:
            last_index = i

        yield last_index
于 2014-12-03T07:29:20.697 回答
1
myList = [687, 687, 683, 683, 677, 662]
unique_sorted_list = sorted(list(set(myList)), reverse = True)
result = []
for i in range(len(unique_sorted_list)):
    if i == 0:
        result.append((unique_sorted_list[i], i))
    else:
        result.append((unique_sorted_list[i], unique_sorted_list[i-1] - unique_sorted_list[i] + result[i-1][1]))

result = [j[1] for i in myList for j in result if i==j[0]]  
print result

我们得到输出为:

[0, 0, 4, 4, 10, 25]
于 2014-12-03T07:33:11.957 回答