this question之后的讨论让我感到疑惑,所以我决定运行一些测试,比较set((x,y,z))
和{x,y,z}
在Python中创建集合的创建时间(我使用的是Python 3.7).
我用time
和timeit
比较了这两种方法.
test1 = """
my_set1 = set((1, 2, 3))
"""
print(timeit(test1))
Result: 0.30240735499999993
test2 = """
my_set2 = {1,2,3}
"""
print(timeit(test2))
Result: 0.10771795900000003
因此,第二种方法比第一种方法高almost 3 times faster.
* Note: I only show the results of the timeit
tests since they are averaged over many samples, and thus perhaps more reliable, but the results when testing with time
showed similar differences in both cases.
Edit:我知道this similar question,虽然它回答了我最初问题的某些方面,但它并没有涵盖所有方面.问题中没有提到集合,而且由于empty sets在python中没有文字语法,我很好奇使用文字创建集合与使用set()
方法有什么不同(如果有的话).此外,我想知道set((x,y,z)
中tuple parameter的处理是如何在幕后进行的,以及它对运行时的可能影响.