简体   繁体   English

在列表中迭代(item,others)

[英]Iterate over (item, others) in a list

Suppose I have a list: 假设我有一个列表:

l = [0, 1, 2, 3]

How can I iterate over the list, taking each item along with its complement from the list? 如何迭代列表,从列表中获取每个项目及其补充? That is, 那是,

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

would print 会打印

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

Ideally I'm looking for a concise expression that I can use in a comprehension. 理想情况下,我正在寻找一个简洁的表达,我可以在理解中使用。

This is quite easy and understandable: 这很容易理解:

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

You could make an iterator out of this if you insist: 如果你坚持,你可以用这个做迭代器:

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

Giving it's usage: 给它的用法:

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

Answering my own question, it is possible to use itertools.combinations exploiting the fact that the result is emitted in lexicographical order: 回答我自己的问题,有可能使用itertools.combinations来利用结果以字典顺序发出的事实:

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

However, this is fairly obscure; 然而,这是相当模糊的; nightcracker's solution is a lot easier to understand for the reader! nightcracker的解决方案是一个更容易理解的读者!

What about 关于什么

>>> [(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])]

OK, that's a gazillion of tests and @nightcracker's solution is likely more efficient, but eh... 好吧,这是一项大量的测试,@ nightcracker的解决方案可能更有效,但是......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM