2015-11-02 76 views
-2

我想算一個給定的列表,如:合計表按訂單

list = [1 , 1, 2, 2, 4, 2, 3, 3] 

,其結果將是:

2122141223 

那麼這段代碼的功能是計數按訂單多少次X數字在行中。在上面的例子中有1個,然後又1,所以= 2(次數的數量)1這是我做了什麼,我不知道如何繼續(數字本身)

list = [1, 1, 2, 1, 4, 6] 
i = 0 
n = len(list) 
c = 1 
list2 =[] 
while i in range(0, n) and c in range (1 , n): 
    if list[i] == list[i+1]: 
     listc= i+c 
     listx = str(listc) 
     list2.insert(i, i+c) 
     i += 1 
     c += 1 
    else: 
     f = i + 1 
     i += 1 
     c += 1 

我想要做的是檢查數字是否相同的循環,如果他們將繼續下一個數字,直到它運行不同的數字。

+0

請,表演,你有什麼話已經嘗試過,什麼不起作用 – soon

+0

到目前爲止,我設法做一個循環,只是複製另一個列表...我基本卡住 – mars

+0

@mars編輯到你的問題,它是不可讀的,沒有格式。 – TankorSmash

回答

3

您可以使用Python groupby功能如下:

from itertools import groupby 

my_list = [1, 1, 2, 2, 4, 2, 3, 3] 
print ''.join('{}{}'.format(len(list(g)), k) for k,g in groupby(my_list)) 

給你以下的輸出:

2122141223 

k給你鑰匙(例如1,2,4,2, 3)和g給出了一個迭代器。通過將其轉換爲列表,其長度可以確定。

使用或不使用的groupby功能,你可以做到以下幾點:

my_list = [1, 1, 2, 2, 4, 2, 3, 3] 

current = my_list[0] 
count = 1 
output = [] 

for value in my_list[1:]: 
    if value == current: 
     count += 1 
    else: 
     output.append('{}{}'.format(count, current)) 
     current = value 
     count = 1 

output.append('{}{}'.format(count, current)) 
print ''.join(output) 
+0

謝謝你的答案,但既然我們沒有使用「進口」,但我不認爲我現在可以使用它,有沒有另一種方式? – mars