如何将唯一计数附加到列表中的字符串结尾?

时间:2017-09-19 20:01:31

标签: python python-3.x list

我正在寻找类似于this question的东西,但是在Python中。

我有一个包含重复元素的列表:

["Apple", "Orange", "Apple", "Pear", "Banana", "Apple", "Apple", "Orange"]

我正在寻找能够给我的列表表达式或方法:

["Apple 1", "Orange 1", "Apple 2", "Pear 1", "Banana 1", "Apple 3", "Apple 4", "Orange 2"]

显然,保持秩序非常重要。

3 个答案:

答案 0 :(得分:4)

选项1
collections.Counter

from collections import Counter

mapping = {k : iter(range(1, v + 1)) for k, v in Counter(lst).items()} 
lst2 = ['{} {}'.format(x, next(mapping[x])) for x in lst]

print(lst2)
['Apple 1', 'Orange 1', 'Apple 2', 'Pear 1', 'Banana 1', 'Apple 3', 'Apple 4', 'Orange 2']

选项2
itertools.count

juan suggests the use of itertools.count,是上述的一个很好的替代品。

from itertools import count

mapping = {k : count(1) for k in set(lst)}   
lst2 = ['{} {}'.format(x, next(mapping[x])) for x in lst]

print(lst2)
['Apple 1', 'Orange 1', 'Apple 2', 'Pear 1', 'Banana 1', 'Apple 3', 'Apple 4', 'Orange 2']

这与上面的差别在于mapping的定义方式。

答案 1 :(得分:1)

直截了当的方式显而易见:

>>> from collections import Counter
>>> counts = Counter()
>>> x = ["Apple", "Orange", "Apple", "Pear", "Banana", "Apple", "Apple", "Orange"]
>>> new_x = []
>>> for item in x:
...     counts[item] += 1
...     new_x.append(f"{item}{counts[item]}")
...
>>> new_x
['Apple1', 'Orange1', 'Apple2', 'Pear1', 'Banana1', 'Apple3', 'Apple4', 'Orange2']
>>>

答案 2 :(得分:1)

from collections import Counter

data = ["Apple", "Orange", "Apple", "Pear", "Banana", "Apple", "Apple", "Orange"]
a = Counter(data)

for i in range(len(data) - 1, -1, -1):
    index = str(a[data[i]])
    a[data[i]] -= 1
    data[i] += ' ' + index   

现在data等于['Apple 1', 'Orange 1', 'Apple 2', 'Pear 1', 'Banana 1', 'Apple 3', 'Apple 4', 'Orange 2']

这会就地修改给定列表。