Python:根据条件拆分列表?anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]从美学和性能角度来看,根据条件将项目列表拆分为多个列表的最佳方法是什么?相当于:good = [x for x in mylist if x in goodvals]bad = [x for x in mylist if x not in goodvals]有什么更优雅的方法吗?更新:下面是实际的用例,以更好地解释我想要做的事情:# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')images = [f for f in files if f[2].lower() in IMAGE_TYPES]anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
3 回答
慕慕森
TA贡献1856条经验 获得超17个赞
good = [x for x in mylist if x in goodvals]bad = [x for x in mylist if x not in goodvals]
有什么更优雅的方法吗?
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ] IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')images = [f for f in files if f[2].lower() in IMAGE_TYPES] anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
images, anims = [], []for f in files: if f.lower() in IMAGE_TYPES: images.append(f) else: anims.append(f)
set()
if f[1] == 0: continue
UYOU
TA贡献1878条经验 获得超4个赞
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)
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']
添加回答
举报
0/150
提交
取消