我有任意大小的元组。这是一个例子:
ax = ('0','1','1','1','2','2','2','3')
对于 x 轴标签,我想将此元组转换为:
ax = ('0','1','','','2','','','3')
因此,应删除重复项,同时元组大小应保持不变。有没有简单的方法可以做到这一点?
最佳答案
In [12]: seen = set()
In [13]: [x if x not in seen and not seen.add(x) else '' for x in ax]
Out[13]: ['0', '1', '', '', '2', '', '', '3']
这是 Dave Kirby, here 建议的唯一标识符的稍微修改版本。 .
seen.add(x)
添加x
到集seen
。 seen.add
方法返回 None
。所以
在 bool 上下文中,(因为 bool(None)
是 False
), not seen.add(x)
总是True
。因此条件
x not in seen and not seen.add(x)
有一个 bool 值等于
x not in seen and True
相当于
x not in seen
所以条件表达式
x if x not in seen and not seen.add(x) else ''
返回x
如果x
尚未在 seen
中并返回''
如果x
已经在 seen
(然后 x
添加到 seen
)。如果x not in seen
是 False
(也就是说,如果 x
已经在 seen
中)则 seen.add(x)
没有被调用,因为 Python 的 and
短路——任何 False and something
形式的表达式自动为False
无需评估something
.
这也可以写成,不那么简洁,但不复杂,如
def replace_dupes(ax):
result = []
seen = set()
for x in ax:
if x in seen:
result.append('')
else:
seen.add(x)
result.append(x)
return result
ax = ('0','1','1','1','2','2','2','3')
print(replace_dupes(ax))
# ['0', '1', '', '', '2', '', '', '3']
关于python - 删除元组中的以下重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935617/