2014-12-03 43 views
1

我有这样的数字列表:如何重新编号反向排序的整数列表?

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

它是按降序排列,并有许多数字。

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

有没有办法做到这一点?

编辑:

其实,我要代表new_list为[0,0,4,4,10,25..],使得最高元素的收益为0,那么下一个元素是两个数字的原始列表+在new_list以前数之差,就像我们通过做(687-683) + 0等等得到4一样。怎么做?

+0

只是迭代列表。 – 2014-12-03 07:27:23

回答

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] 
+0

@LindaSu我很高兴能帮上忙。如果答案有帮助,您可以接受或提出答案。谢谢。 – 2014-12-03 22:27:14

+0

@琳达苏感谢琳达 – 2014-12-03 22:48:46

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 
+0

完美!非常感谢。 – 2014-12-03 07:33:58

+0

但有一个问题,是否可以添加从0开始的数字,下一个数字是原始列表中的两个数字+ new_list中的前一个数字的差异?就像这个例子一样,它是:[0,0,4,4,10,25]? – 2014-12-03 08:05:51

+0

@LindaSu:当然!查看更新。 – Ryan 2014-12-03 15:18:29