在列表中迭代(item,others)

时间:2012-08-31 20:22:22

标签: python sequence itertools complement

假设我有一个清单:

l = [0, 1, 2, 3]

如何迭代列表,从列表中获取每个项目及其补充?也就是说,

for item, others in ...
    print(item, others)

会打印

0 [1, 2, 3]
1 [0, 2, 3]
2 [0, 1, 3]
3 [0, 1, 2]

理想情况下,我正在寻找一种可以理解的简洁表达方式。

3 个答案:

答案 0 :(得分:13)

这很容易理解:

for index, item in enumerate(l):
    others = l[:index] + l[index+1:]

如果你坚持,你可以制作一个迭代器:

def iter_with_others(l):
    for index, item in enumerate(l):
        yield item, l[:index] + l[index+1:]

给出它的用法:

for item, others in iter_with_others(l):
    print(item, others)

答案 1 :(得分:3)

回答我自己的问题,可以使用itertools.combinations利用结果以字典顺序发出的事实:

from itertools import combinations
zip(l, combinations(reversed(l), len(l) - 1))

然而,这是相当模糊的; nightcracker的解决方案是很多让读者更容易理解!

答案 2 :(得分:2)

怎么样?
>>> [(i, [j for j in L if j != i]) for i in L]
[(0, [1, 2, 3]), (1, [0, 2, 3]), (2, [0, 1, 3]), (3, [0, 1, 2])]

好的,这是大量的测试,@ nightcracker的解决方案可能更有效,但是......嗯......