2013-11-23 29 views
0

建議在Python 2.6討好轉換這個首發名單:如何修改這條巨蟒列表順序

lis = ['1','2','2','2','3','3','4','7','9'] 

到:

lis2 = ['1_1','2_1','2_2','2_3','3_1','3_2','4_1','7_1','9_1'] 

注意,該項目是字符串

+7

向我們展示你的代碼爲止。這不是一個編程服務。 –

+0

您的序列已排序。它會一直如此嗎?如果不是,編號是爲了獨特的價值還是爲了團體? –

+0

我沒有這樣使用它。作爲初學者,我從我非常感謝的其他人的例子中學到很多東西。我無法超越將字符串頻率轉換爲字典:diction = {} for char in lis: diction [char] = lis.count(char) – user3024732

回答

1

使用collections.defaultdict

>>> from collections import defaultdict 
>>> 
>>> lis = ['1','2','2','2','3','3','4','7','9'] 
>>> lis2 = [] 
>>> cnt = defaultdict(int) 
>>> for x in lis: 
...  cnt[x] += 1 
...  lis2.append('{}_{}'.format(x, cnt[x])) 
... 
>>> lis2 
['1_1', '2_1', '2_2', '2_3', '3_1', '3_2', '4_1', '7_1', '9_1'] 
1

你可以使用itertools.groupby()enumerate()

from itertools import groupby 

['{}_{}'.format(i, count) for _, g in groupby(lis) for count, i in enumerate(g, 1)] 

演示:

>>> ['{}_{}'.format(i, count) for _, g in groupby(lis) for count, i in enumerate(g, 1)] 
['1_1', '2_1', '2_2', '2_3', '3_1', '3_2', '4_1', '7_1', '9_1'] 

這不使用額外的內存,但需要你的羣體是不同的和排序;如果有兩次運行2,則每次運行都單獨編號。

0

defaultdict麻花鑽:

from collections import defaultdict 
from itertools import count 

data = ['1','2','2','2','3','3','4','7','9']  
result = map(lambda L, dd=defaultdict(lambda: count(1)): '{}_{}'.format(L, next(dd[L])), data) 
# ['1_1', '2_1', '2_2', '2_3', '3_1', '3_2', '4_1', '7_1', '9_1']