python - 在列表中查找唯一的元组(忽略顺序),同时在 python 中保留其他元组的原始顺序?

标签 python tuples list-comprehension

假设我有一个看起来像这样的列表:

a = [(1,2),(3,1),(2,1),(4,5),(9,3),(1,3)]

然后,我想要这样的东西:

b = [(1,2),(3,1),(4,5),(9,3)]

非常感谢!

最佳答案

b = []
seen = set()
for t in a:
    s = tuple(sorted(t))
    if s not in seen:
        seen.add(s)
        b.append(t)

seen = set()
b = [t for t in a if tuple(sorted(t)) not in seen and not seen.add(tuple(sorted(t)))]

关于python - 在列表中查找唯一的元组(忽略顺序),同时在 python 中保留其他元组的原始顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961185/

相关文章:

python - 为什么分配给我的全局变量在 Python 中不起作用?

python - 在 python 中,如果两个列表都包含公共(public)元素,则从两个元组列表中选取元组

Python:从不考虑顺序的 "set of tuples"生成 "list of tuples"

python - 使用没有迭代变量的列表理解

loops - 从 Python 3.x 中的另一个列表中删除单独的项目列表

python - Docker文档中的Python缩进错误

python - 使用 pandas 中 dataframe1 中某一列的值查找 dataframe2 中特定列的值

python - 如何公开具有多个参数的 dbus 方法?

python - 负边界切片

python - 从矩阵到单行字典