python - 在循环中使用 Python 中的 set

标签 python dataset

我在 Python 中有以下列表:

[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]

我想将它们分组到 [[1,2,7],[3,4,6,9]]

我执行此操作的代码如下所示:

l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
    for lfi in lf:
        if lfi.intersection(set(li)):
            lfi=lfi.union(set(li))
            break
    else:
        lf.append(set(li))

lf 是我的最终名单。我在 l 和 lf 上循环,当我发现 l 的一个元素和 lf 的另一个元素之间的交集时,我想合并它们(并集)

但我不明白为什么这不起作用。列表 l 的第一个 to 元素正在使用 append 命令插入,但并集不起作用。 我的最终列表 lf 看起来像 [set([1, 2]), set([3, 4])]

这似乎是很基础的东西,但我对集合不熟悉。 我感谢任何帮助

谢谢

最佳答案

问题出在这里:

lfi=lfi.union(set(li))

您没有修改集合。您正在创建一个新集,然后将其丢弃。原始集合仍在 lf 数组中。改用更新:

lfi.update(li)

这会修改原始集而不是创建新集。进行此更改后的结果:

[set([1, 2, 7]), set([9, 3, 4, 6])]

关于python - 在循环中使用 Python 中的 set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2519682/

相关文章:

c# - 如何在 Java 中使用 C# 数据集?

python - 收到 Cassandra 已准备好的声明

python - 带有 tk 的窗口以获取文本

python - 按子字符串聚合 json 元素

c# - 数据集上的动态 SQL

python - load_digits() 和 fetch_mldata ("MNIST Original"有什么区别)

dataset - 使用 tcpreplay 进行真实跟踪互联网数据集

python - 类(class)/ self 问题

python - Python 中的数据包嗅探器

c# - LINQ 是否使用 DataRelations 来优化联接?