2014-12-03 44 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