简体   繁体   中英

How to append unique counts to end of strings in a list?

I'm looking for something similar to this question , but in Python.

I have a list with repeated elements:

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

I'm looking for a list expression or a methodology that will give me:

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

Obviously, preserving order is very important.

Option 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']

Option 2
itertools.count

juan suggests the use of itertools.count , a great alternative to the above.

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

The difference between this and the one above is in the manner in which mapping is defined.

The straightforward way seems obvious enough:

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

Now data is equal to ['Apple 1', 'Orange 1', 'Apple 2', 'Pear 1', 'Banana 1', 'Apple 3', 'Apple 4', 'Orange 2'] .

This modifies the given list in-place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM