嵌套循环遍历集合列表
Nested loop through list of sets
我最近读到的不是做以下事情的好习惯:
for i in xrange(len(string-or-list)):
#do something with string-or-list[i]
我明白了。但是当涉及到嵌套循环时,我不这么认为。
考虑一组集合 h
。我想消除所有那些作为其他集合子集的集合。这就是我所做的:
for x in xrange(len(h)-1,-1,-1):
for y in xrange(x):
if h[x] <= h[y]: h[x] = set()
elif h[x] > h[y]: h[y], h[x] = h[x], set()
return filter(None, h)
我该怎么做才能让它更像 pythonic?我虽然考虑使用 reversed
和 enumerate
,但我不知道如何停止对 x
之前元素的第二个循环。
或者我应该以不同的方式做整件事?
更新
我把集合列表做成元组集合解决了这个问题,然后我应用了
return [list(s) for s in h if sum(1 for o in h if set(s) <= set(o)) <= 1]
最 pythonic 的事情是用你想要的集合组成一个新列表。要删除重复项,我们需要一个辅助函数..
def uniq(seq):
memo = []
for i in seq:
if i not in memo:
memo.append(i)
yield i
那我们就可以为所欲为了
return [s for s in uniq(h) if not any(s < o for o in h)]
很好而且是 pythonic,但是阅读您的初始代码看起来您正在寻找子集(而不是严格的子集)。
这里有一种方法可以解释子集这个词的通常含义:
while True:
for s in h:
if sum(1 for o in h if s <= o) > 1:
h.remove(s)
break
else:
# no subsets were found - we're done
break
我最近读到的不是做以下事情的好习惯:
for i in xrange(len(string-or-list)):
#do something with string-or-list[i]
我明白了。但是当涉及到嵌套循环时,我不这么认为。
考虑一组集合 h
。我想消除所有那些作为其他集合子集的集合。这就是我所做的:
for x in xrange(len(h)-1,-1,-1):
for y in xrange(x):
if h[x] <= h[y]: h[x] = set()
elif h[x] > h[y]: h[y], h[x] = h[x], set()
return filter(None, h)
我该怎么做才能让它更像 pythonic?我虽然考虑使用 reversed
和 enumerate
,但我不知道如何停止对 x
之前元素的第二个循环。
或者我应该以不同的方式做整件事?
更新
我把集合列表做成元组集合解决了这个问题,然后我应用了
return [list(s) for s in h if sum(1 for o in h if set(s) <= set(o)) <= 1]
最 pythonic 的事情是用你想要的集合组成一个新列表。要删除重复项,我们需要一个辅助函数..
def uniq(seq):
memo = []
for i in seq:
if i not in memo:
memo.append(i)
yield i
那我们就可以为所欲为了
return [s for s in uniq(h) if not any(s < o for o in h)]
这里有一种方法可以解释子集这个词的通常含义:
while True:
for s in h:
if sum(1 for o in h if s <= o) > 1:
h.remove(s)
break
else:
# no subsets were found - we're done
break