迭代集合/剩余集合的 pythonic 方法

标签 python

执行以下操作的干净方法是什么:

def foo(aSet) :
    for a in aSet:
        for remaining in aSet - {a} :
            doSomething(a,remaining)

我在想一定有某种方法可以把它写成一个 for 循环?

最佳答案

aSet = {1,2,3}
[[i,j] for i in aSet for j in aSet if j != i]
#=> [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

在您的情况下,您需要一个生成器

(doSomething(i, j) for i in aSet for j in aSet if j != i)

关于迭代集合/剩余集合的 pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36388394/

相关文章:

python - 使用 Django Auth Ldap 将 LDAP 用户映射到 Django 用户

python - 使用两个不同颜色的数据集创建 matplotlib 热图

python - 使用 3 个索引对 4 维数组进行切片时会发生什么?

python - Pandas 列值位于另一个数据帧列的值之间

python - Anaconda:从 PyPi 包构建时出错 ("Package XY missing in current linux-64 channels")

python - 如何在 python 中的嵌套函数上执行 %lprun 工作?

python - 随机化/改组 Pandas 数据框中的行

python - 有没有一种更简单的方法可以将列表随机拆分为子列表而无需在 python 中重复元素?

python - fir2 从 matlab 到 python

python - 在 Python 中使用 dlib 训练对象检测器