1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
from functools import reduce
from operator import add, concat, iadd
from itertools import chain
import functools
import itertools
import operator
rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def f():
return rows
# these should match
def flatten_via_generator(rows):
return (col for row in rows for col in row)
def flatten_via_list_comp(rows):
return [col for row in rows for col in row]
def flatten_via_set_comp(rows):
return {col for row in rows for col in row}
def flatten_with_function_source():
return (col for row in f() for col in row)
def flatten_via_sum(rows):
return sum(rows, [])
def flatten_via_chain_splat(rows):
return chain(*rows)
def flatten_via_chain_splat_2(rows):
return itertools.chain(*rows)
def flatten_via_reduce_add(rows):
return reduce(add, rows)
def flatten_via_reduce_add_with_default(rows):
return reduce(add, rows, [])
def flatten_via_reduce_concat(rows):
return reduce(concat, rows)
def flatten_via_reduce_concat_with_default(rows):
return reduce(concat, rows, [])
def flatten_via_reduce_full_namespace(rows):
return functools.reduce(operator.add, rows)
# these should not
def flatten_via_generator_modified(rows):
return (col + 1 for row in rows for col in row)
def flatten_via_generator_modified_2(rows):
return (col for [row] in rows for col in row)
def flatten_via_generator_modified_3(rows):
return (col for row in rows for [col] in row)
def flatten_via_generator_with_if(rows):
return (col for row in rows for col in row if col)
def flatten_via_generator_with_if_2(rows):
return (col for row in rows if row for col in row)
def flatten_via_dict_comp(rows):
return {col: "" for row in rows for col in row}
async def flatten_async_generator(rows):
return (col async for row in rows for col in row)
async def flatten_async_generator_2(rows):
return (col for row in rows async for col in row)
async def flatten_async_generator_3(rows):
return (col async for row in rows async for col in row)
def flatten_via_sum_with_default(rows):
return sum(rows, [1])
def flatten_via_chain_without_splat(rows):
return chain(rows)
def flatten_via_chain_from_iterable(rows):
return chain.from_iterable(rows)
def flatten_via_reduce_iadd(rows):
return reduce(iadd, rows, [])
def flatten_via_reduce_non_empty_default(rows):
return reduce(add, rows, [1, 2, 3])
|