python - 删除元组中的以下重复项

标签 python arrays tuples

我有任意大小的元组。这是一个例子:

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到集seenseen.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 seenFalse (也就是说,如果 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/

相关文章:

python - 使用 Python 以外的语言为 Sublime Text 3 创建插件

arrays - 当元素是元组时扩展数组受限

javascript - 为什么在 javascript 中过滤扩展数组的类的对象调用它的构造函数?

Python匹配字符串中的元组

python - Pandas groupby 两列然后获取值的字典

python - 如何使用 opencv 将 Monospace 字体插入到图像中?

sql - 在 postgresql ...query... 中加入两个单独的查询(可能或不可能)

scala - 迭代列表,返回当前元素、下一个元素以及当前元素之前的元素

python - 乘以相邻元素

python - 我如何通过python中的ssh隧道连接到服务器