[英]How to append unique counts to end of strings in a list?
I'm looking for something similar to this question , but in Python. 我正在寻找类似于此问题的内容 ,但使用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 选项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 选项2
itertools.count
juan suggests the use of itertools.count
, a great alternative to the above. juan建议使用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']
The difference between this and the one above is in the manner in which mapping
is defined. 两者之间的区别在于定义mapping
的方式。
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']
. 现在data
等于['Apple 1', 'Orange 1', 'Apple 2', 'Pear 1', 'Banana 1', 'Apple 3', 'Apple 4', 'Orange 2']
。
This modifies the given list in-place. 这样就可以修改给定的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.