如何按顺序修改此python列表

时间:2013-11-23 13:52:52

标签: python list python-2.6

建议请在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']

注意,这些项目是字符串

3 个答案:

答案 0 :(得分: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 :(得分: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次运行,则每次运行都会单独编号。

答案 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']