Python 将列表中的重复项转换为唯一项
我在列表中有以下重复项目列表:Python 将列表中的重复项转换为唯一项,python,arrays,list,Python,Arrays,List,我在列表中有以下重复项目列表: x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"] 我希望获得以下输出: out = ['John_1', "Jill_1", "Ron_1", "John_2", "Jill_2", "John_3", "Tom_1", "Harry_1", "Harry_2"] 我编写了以下代码: from collections import Counter def i
x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
我希望获得以下输出:
out = ['John_1', "Jill_1", "Ron_1", "John_2", "Jill_2", "John_3", "Tom_1", "Harry_1", "Harry_2"]
我编写了以下代码:
from collections import Counter
def iterate_string_duplicates(x):
nl = []
dct = dict(Counter(x))
for k,v in dct.items():
for i in list(range(1,v+1)):
nl.append(k+"_"+str(i))
return nl
但由于使用字典方法,我得到了以下输出:
iterate_string_duplicates(x)
output: ['John_1', 'John_2', 'John_3', 'Jill_1', 'Jill_2', 'Ron_1', 'Tom_1', 'Harry_1', 'Harry_2']
我正在寻找一种初始字符串顺序不会改变的方法。您可以使用的列表理解思想是将计数器与每个名称关联起来。那么它只需要一次通过iterable
>>> from collections import defaultdict
>>> from itertools import count
>>> suffix = defaultdict(lambda: count(1))
>>> x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
>>> [f"{name}_{next(suffix[name])}" for name in x]
['John_1',
'Jill_1',
'Ron_1',
'John_2',
'Jill_2',
'John_3',
'Tom_1',
'Harry_1',
'Harry_2']
与答案类似,我们可以使用从计数1开始的值来确定名称的下一个计数
from collections import defaultdict
names = ["John", "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
counts = defaultdict(lambda : 1)
result = []
for name in names:
result.append(f"{name}_{counts[name]}")
counts[name] += 1
print(result)
或在添加到结果列表之前保留默认值0和增量:
counts = defaultdict(int)
result = []
for name in names:
counts[name] += 1
result.append(f"{name}_{counts[name]}")
与第一个解决方案不同,它将在计数中反映名称的实际计数
输出:
您可以使用普通dict执行以下代码并完成任务-
x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
y = dict()
def get_me_number(item):
if item in y:
y[item] += 1
return y[item]
elif item not in y:
y[item] = 1
return 1
res = list(map(lambda x_item: x_item+str(get_me_number(x_item)),x))
print(res)
x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
y = dict()
def get_me_number(item):
if item in y:
y[item] += 1
return y[item]
elif item not in y:
y[item] = 1
return 1
res = list(map(lambda x_item: x_item+str(get_me_number(x_item)),x))
print(res)