我想遍历list
并将当前元素与其他元素分开。 像这样:Python独占循环
for e in the_list:
function_call(e, <the_list but e>)
有一种优雅的方式来做到这一点?
我想遍历list
并将当前元素与其他元素分开。 像这样:Python独占循环
for e in the_list:
function_call(e, <the_list but e>)
有一种优雅的方式来做到这一点?
你可以使用enumerate
,切片名单:
for index, elem in enumerate(the_list):
function_call(elem, the_list[:index] + the_list[index + 1:])
当'index == 0'时,'the_list [:index]'与'[elem]'是否相同? – 2013-04-22 17:55:27
@MarkusMeskanen它会是'[]'。 – 2013-04-22 17:56:06
@MarkusMeskanen:'the_list [:0]'为空。它与'the_list [:]'不一样。 – Blender 2013-04-22 17:56:08
一个很好的解决方案,它读取(合理的)好,不需要与指数乱搞。
>>> from itertools import combinations
>>> data = [1, 2, 3, 4]
>>> for item, rest in zip(data,
reversed(list(combinations(data, len(data)-1)))):
... print(item, rest)
...
1 (2, 3, 4)
2 (1, 3, 4)
3 (1, 2, 4)
4 (1, 2, 3)
+1用于忽略任意数量的元素。 – Blender 2013-04-22 18:06:46
我不是100%确定这是重复的,因为这需要单独知道元素... – 2013-04-22 18:04:57
@JonClements:这是一个很好的观点。尽管我们总是可以用这个问题的答案结果来压缩列表,但也许我们中的一些人(包括我自己)对触发器有一点敏感,因为很明显我们可以同时获得这两个结果。 – DSM 2013-04-22 18:08:40
@DSM它比这更复杂一点,因为顺序实际上与你想要的相反,因此我的答案。 – 2013-04-22 18:09:56