假设我有一个列表。
temp = ['A', 'B', 'A', 'B', 'A', 'B']
我正在寻找一种方法来加入里面的字符串的计数。
预期输出:
['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3']
我能够通过使用列表理解来解决它,但我正在寻找一种无需指定列表的方法 [1, 1, 2, 2, 3, 3]
。有可能吗?
[j + "_" + str(i) for i, j in zip([1, 1, 2, 2, 3, 3], temp)]
最佳答案
您可以使用 collections.defaultdict
带有 for
循环:
from collections import defaultdict
L = ['A', 'B', 'A', 'B', 'A', 'B']
dd = defaultdict(int)
res = []
for item in L:
dd[item] += 1
res.append(f'{item}_{dd[item]}')
print(res)
['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3']
关于python - 如何为列表中的每个唯一 val 添加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53098757/