可能重複:
python equivalent of filter() getting two output lists (i.e. partition of a list)分區陣列基於謂詞
我有在python陣列,並希望將其分割成兩個陣列,一個其中元素的謂詞匹配另一個元素沒有。
是否有一個更簡單的方法(或更Python)比下面
>>> def partition(a, pred):
... ain = []
... aout = []
... for x in a:
... if pred(x):
... ain.append(x)
... else:
... aout.append(x)
... return (ain, aout)
...
>>> partition(range(1,10), lambda x: x%3 == 1)
([1, 4, 7], [2, 3, 5, 6, 8, 9])
呵呵,我試圖與發帖無法找到它之前搜索 - 謝謝! –