我想遍歷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