4

listをループして、現在の要素を他の要素から分離したい。このような :

for e in the_list:
    function_call(e, <the_list but e>)

それを行うエレガントな方法はありますか?

4

2 に答える 2

7

リストを使用enumerateしてスライスすることができます:

for index, elem in enumerate(the_list):
    function_call(elem, the_list[:index] + the_list[index + 1:])
于 2013-04-22T17:54:06.350 に答える
4

(合理的に)よく読み、インデックスをいじる必要のない優れたソリューション。

>>> 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)
于 2013-04-22T18:05:57.297 に答える