我正在制作一个平台游戏,目前正在创建一个函数,该函数将通过接受对象或对象列表来处理绘图,并对所有对象执行渲染函数。
我创建了一个嵌套的 for 循环来处理输入,但我无法创建一个可以更快地处理这个问题的列表理解;请帮忙。
def flatten(*args):
l = []
for j in args:
if "__iter__" not in dir(j):
j = [j]
for i in j:
l.append(i)
return l
def flatten(*args):
return [i for j in args for i in (j if isinstance(j, (list, tuple, set, dict)) else [j])]
为了潜在地简化这一点,我会从给定的参数中屈服,而不是理解,如果这是一个问题,请原谅。
类似:
def flatten_new(*args):
for arg in args:
try:
yield from arg
except TypeError:
yield arg
这似乎让我们能够创建相同的结果。
def flatten_orig(*args):
l = []
for j in args:
if "__iter__" not in dir(j):
j = [j]
for i in j:
l.append(i)
return l
def flatten_new(*args):
for arg in args:
try:
yield from arg
except TypeError:
yield arg
big_args = list(range(100)) + [list(range(10)) for _ in list(range(10))]
print(flatten_orig(*big_args) == list(flatten_new(*big_args)))
运气好的话应该是
True
现在让我们看看它是否更快:
import timeit
setup = """
def flatten_orig(*args):
l = []
for j in args:
if "__iter__" not in dir(j):
j = [j]
for i in j:
l.append(i)
return l
def flatten_new(*args):
for arg in args:
try:
yield from arg
except TypeError:
yield arg
big_args = list(range(100)) + [list(range(10)) for _ in list(range(10))]
"""
print(timeit.timeit("flatten_orig(*big_args)", setup=setup, number=10_000))
print(timeit.timeit("list(flatten_new(*big_args))", setup=setup, number=10_000))
给我的结果如下:
8.682825100000628
0.3459608999983175
表明新策略在使用大量参数时速度更快