UYOU
以下是懒惰迭代器方法:from itertools import teedef split_on_condition(seq, condition):
l1, l2 = tee((condition(item), item) for item in seq)
return (i for p, i in l1 if p), (i for p, i in l2 if not p)它每项计算一次条件,并返回两个生成器,首先从条件为真的序列中产生值,另一个生成条件为false的序列。因为它很懒,所以您可以在任何迭代器上使用它,甚至是无限迭代器:from itertools import count, islicedef is_prime(n):
return n > 1 and all(n % i for i in xrange(2, n))primes, not_primes = split_on_condition(count(), is_prime)
print("First 10 primes", list(islice(primes, 10)))print("First 10 non-primes", list(islice(not_primes, 10)))通常情况下,非延迟列表返回方法更好:def split_on_condition(seq, condition):
a, b = [], []
for item in seq:
(a if condition(item) else b).append(item)
return a, b编辑:对于通过某些键将项拆分为不同列表的更具体的用法,下面是一个通用函数:DROP_VALUE = lambda _:_def split_by_key(seq, resultmapping, keyfunc, default=DROP_VALUE):
"""Split a sequence into lists based on a key function.
seq - input sequence
resultmapping - a dictionary that maps from target lists to keys that go to that list
keyfunc - function to calculate the key of an input value
default - the target where items that don't have a corresponding key go, by default they are dropped
"""
result_lists = dict((key, []) for key in resultmapping)
appenders = dict((key, result_lists[target].append) for target, keys in resultmapping.items() for key in keys)
if default is not DROP_VALUE:
result_lists.setdefault(default, [])
default_action = result_lists[default].append else:
default_action = DROP_VALUE for item in seq:
appenders.get(keyfunc(item), default_action)(item)
return result_lists用法:def file_extension(f):
return f[2].lower()split_files = split_by_key(files, {'images': IMAGE_TYPES}, keyfunc=file_extension, default='anims')
print split_files['images']print split_files['anims']