python中一个非常常见的模式是:
for something in ['an', 'iterable']:
func(something)我几乎总是将可迭代性看作列表(如本例中所示),但它很可能是元组、集合或其他东西。清单是最有表现力和力度的一种方法吗?
同样,我经常看到以下情况:
if something_else in ['another', 'iterable']:
func(something_else)在这种情况下,我们实际上是在搜索something_else (注意if而不是for),如果可迭代是一个集合(例如,if x in {...}:),那么它的性能可能会更好。然而,对于非常小的数量来说,这不一定是正确的。一张清单仍然是做这件事的必经之路吗?
发布于 2019-05-01 01:18:51
我想timeit是一件事。以下是研究结果:
$ python -m timeit "x=True if 'my_variable' in ['just', 'three', 'options'] else False"
10000000 loops, best of 3: 0.0643 usec per loop
$ python -m timeit "x=True if 'my_variable' in ('just', 'three', 'options') else False"
10000000 loops, best of 3: 0.0645 usec per loop
$ python -m timeit "x=True if 'my_variable' in {'just', 'three', 'options'} else False"
10000000 loops, best of 3: 0.113 usec per loop较长的一套备选方案:
$ python -m timeit "x=True if 'my_variable' in ['a', 'much', 'longer', 'list', 'of', 'choices', 'but', 'still', 'nothing', 'crazy', 'and', 'perhaps', 'you', 'could', 'actually', 'find', 'some', 'ridiculous', 'code', 'like', 'this', 'in', 'the', 'wild'] else False"
1000000 loops, best of 3: 0.264 usec per loop
$ python -m timeit "x=True if 'my_variable' in ('a', 'much', 'longer', 'list', 'of', 'choices', 'but', 'still', 'nothing', 'crazy', 'and', 'perhaps', 'you', 'could', 'actually', 'find', 'some', 'ridiculous', 'code', 'like', 'this', 'in', 'the', 'wild') else False"
1000000 loops, best of 3: 0.262 usec per loop
$ python -m timeit "x=True if 'my_variable' in {'a', 'much', 'longer', 'list', 'of', 'choices', 'but', 'still', 'nothing', 'crazy', 'and', 'perhaps', 'you', 'could', 'actually', 'find', 'some', 'ridiculous', 'code', 'like', 'this', 'in', 'the', 'wild'} else False"
1000000 loops, best of 3: 0.82 usec per loop元组和列表执行相同的操作,而且它们显然比集合更快。我可以想象这是因为这些电视机的开销要大得多,因此当N很小的时候就不那么实用了。有关比较元组和列表的更多与性能相关的信息,请参见Are tuples more efficient than lists in Python?上的各种答案
至于风格,我不认为有什么区别。
发布于 2019-05-01 05:59:57
忘记关于时间的争论,它们与您正在做的事情无关,而且它们可能因不同的Python实现而有所不同。最好是对可读性进行优化
为了回答你的问题,我相信这份清单是最“毕达通”的。大多数Python开发人员使用列表来做任何事情,没有人会看你的代码并认为它很奇怪。列表方括号([ ])在扫描代码时也非常清晰,易于识别。set括号({ })可以与dict混淆,初学者可能不熟悉这种符号。元组括号是一个奇怪的括号:所有地方都使用括号,Python和语法可能会很混乱。一个项目的元组需要一个逗号:('item',)
话虽如此,“毕多尼”就像一种时尚:今天流行的东西可能几年后就不流行了,因为语言的变化、人的变化、图书馆的变化等等。我是尽可能多地使用“适当”类型的超级粉丝。你是在处理一个集合(在数学意义上)还是一个列表?如果是集合,则使用set否则为list。
发布于 2019-05-01 05:01:05
考虑到没有显著差异,如s所示,列表可能更好。列表的使用比较常见,因此,与用于更多事情的圆括号相比,方括号可以更容易识别为集合。
https://stackoverflow.com/questions/55930239
复制相似问题