我想做的是转换一个数组
['x', 'y', 'z', 'x', 'z']
进入:
['x1', 'y', 'z1', 'x2', 'z2']
意义
- 如果某个事件(此处为
'y'
)不重复,则保持原样。 - 如果出现不止一次(此处为
'x'
或'z'
),则在它们后面加上排名。
在我的例子中,数组大小会很小(少于 20 个元素,没有性能问题)。
是否可以用优雅、简短的 Python 表达式来实现?
编辑:
虽然我不知道它是否优雅,但我现在终于编码了这个(没有导入,只有一个字典):
def index_duplicates( l ):
def get_indexed( d, s ):
c = d[s]
if c: d[s] = c + 1
return s + str(c) if c else s
d = {}
for s in l: d[s] = 1 if s in d else 0
return (get_indexed(d, s) for s in l)
这样:
[x for x in index_duplicates(l)]
返回结果。
最佳答案
原始版本 - O(n^2)
没有导入,我们可以进行以下简单的实现:
arr = ['x', 'y', 'z', 'x', 'z']
out = []
for i in range(len(arr)):
c = arr[i]
if arr.count(c) > 1:
out.append(c + str(arr[:i].count(c) + 1))
else:
out.append(c)
>>> out
['x1', 'y', 'z1', 'x2', 'z2']
高效版 - O(n)
如果我们想要有更好的时间复杂度,我们可以遍历一次列表以获得列表中每个唯一字符的总数。然后,我们可以第二次遍历列表,在进行过程中缓存字符数并使用它来获得答案。
arr = ['x', 'y', 'z', 'x', 'z']
out = []
totals = dict()
freqs = dict() # Track all character counts
# Get the total count of every unique character in the list
for i, c in enumerate(arr):
if c in totals:
totals[c] += 1
else:
totals[c] = 1
for i, c in enumerate(arr):
total = totals[c] # Get total character count
# Count how many have been seen so far during the second traversal
if c in freqs:
freqs[c] += 1
else:
freqs[c] = 1
out.append(c + str(freqs[c]) if total > 1 else c)
>>> out
['x1', 'y', 'z1', 'x2', 'z2']
关于python - 一种将重复项转换为 Python 索引的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296981/