我正在回答这个问题 https://stackoverflow.com/questions/59925390/how-to-count-different-elements-in-list-of-lists/59925564?noredirect=1#comment106101518_59925564,当我测试解决方案的时间时,我发现了与我认为正确的矛盾。
提出问题的人想要找到一种方法来知道另一个列表中包含多少个不同的列表。 (欲了解更多信息,您可以检查问题 https://stackoverflow.com/questions/59925390/how-to-count-different-elements-in-list-of-lists/59925564?noredirect=1#comment106101518_59925564)
我的回答基本上是这个功能:
def how_many_different_lists(lists):
s = set(str(list_) for list_ in lists)
return len(s)
现在,当我测量运行时间并将其与基本相同的函数进行比较时,情况出现了,但将列表而不是生成器作为参数传递给 set():
def the_other_function(lists):
s = set([str(list_) for list_ in lists])
return len(s)
这是我用于测试功能的装饰器:
import time
def timer(func):
def func_decorated(*args):
start_time = time.clock()
result = func(*args)
print(time.clock() - start_time, "seconds")
return result
return func_decorated
这是给定输入的结果:
>>> list1 = [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
>>> how_many_different_lists(list1)
6.916326725558974e-05 seconds
2
>>> the_other_function(list1)
3.882067261429256e-05 seconds
2
即使对于更大的列表:
# (52 elements)
>>> list2= [[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2],[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
>>> how_many_different_lists(list2)
0.00023560132331112982 seconds
2
>>> the_other_function(list2)
0.00021329059177332965 seconds
2
现在,我的问题是:为什么第二个例子比第一个例子更快?由于“按需”生产元素,发电机难道不应该更快吗?我曾经认为制作一个列表并迭代它会比较慢。
PS:我已经测试了很多次,得到的结果基本相同。