eca*_*mur 10 python sequence complement python-itertools
假设我有一个列表:
l = [0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
如何迭代列表,从列表中获取每个项目及其补充?那是,
for item, others in ...
print(item, others)
Run Code Online (Sandbox Code Playgroud)
会打印
0 [1, 2, 3]
1 [0, 2, 3]
2 [0, 1, 3]
3 [0, 1, 2]
Run Code Online (Sandbox Code Playgroud)
理想情况下,我正在寻找一个简洁的表达,我可以在理解中使用.
orl*_*rlp 13
这很容易理解:
for index, item in enumerate(l):
others = l[:index] + l[index+1:]
Run Code Online (Sandbox Code Playgroud)
如果你坚持,你可以用这个做迭代器:
def iter_with_others(l):
for index, item in enumerate(l):
yield item, l[:index] + l[index+1:]
Run Code Online (Sandbox Code Playgroud)
给它的用法:
for item, others in iter_with_others(l):
print(item, others)
Run Code Online (Sandbox Code Playgroud)