gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:09 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com