有趣我也想出了其他方法。
>>> from collections import OrderedDict as OD
>>> attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))
,如果你想扭转你可以做到这一点
>>> reverse = OD(attributes.items()[::-1])
或更Python的方法:
>>> reverse = OD(reversed(attributes.items()))
注意到你不需要创建list
项目已经是一个列表,而reversed
是一个生成器OrderedDict
将简单迭代到它生成新的字典。
两者都产生类似的时间。
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reverse = OD(attributes.items()[::-1])"
10000 loops, best of 3: 54.8 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reverse = OD(reversed(attributes.items()))"
10000 loops, best of 3: 54.4 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reversed_attributes=OD(reversed(list(attributes.items())))"
10000 loops, best of 3: 54.4 usec per loop
如果要反转:
>>> invert = OD(zip(*zip(*attributes.items())[::-1]))
或更Python:
>>> invert = OD(map(reversed, attributes.items()))
双方再次产生类似的定时。
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "invert = OD(zip(*zip(*attributes.items())[::-1]))"
10000 loops, best of 3: 57 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "invert = OD(map(reversed, attributes.items()))"
10000 loops, best of 3: 56.8 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "inverted_attributes=OD([reversed(item) for item in attributes.items()])"
10000 loops, best of 3: 55.8 usec per loop
您可以结合使用这两种方法来反转和反转。
这有效,但效率不高?通过使用反转(列表(a.items()))这是否产生了很多开销,所以不是pythonic? reverse_attributes也一样。
东西能产生大量的开销,是对另一方面的东西可以非常非常有效的,而不是很Python的Python的,这个词已经被有点虐待,但是那只是我的意见
使出wikipedia:
Python社区中的一个常见新词是pythonic,它可以与程序风格有广泛的含义。要说代码是pythonic,就是说它很好地使用了Python成语,它是自然的或者表现出流畅的语言。同样,说一个接口或语言特性,它是pythonic是说,它适用于Python成语,它的使用与其他语言良好的衔接。
相反,unpythonic代码的一个标志是它试图用Python编写C++(或Lisp,Perl或Java)代码 - 也就是说,它提供了一个粗略的转录,而不是来自另一种语言的表单的惯用翻译。pythonicity的概念与Python的极简主义可读性哲学紧密相连,并且避免了“有多种方法可行”的方法。无法读取的代码或难以理解的习惯用法是不合理的。
为:
但这种减少表现为我们扩大规模?
这很难说,不知道为什么要做出这样的变换,或者判断你的系统的一个组成部分,从根本上裸minimun他们增加线性时间/空间开销可能会或可能不会如果条目数量仍然很少,那么没有问题,但如果在每次请求时,假设这发生在网络服务器上,那么您的这些操作是在大量的字符上进行的,这可能会非常严酷,并且可能需要重新设计以避免这个。
'逆转(名单(a.items()))'产生很大的开销,因为你无需创建一个'list',然后它迭代相反。删除'list'构造函数会直接反转'items'(不需要中间复制)。同样,当初始化新OrderedDict时,你想使用一个生成器表达式(w/o'[]'),而不是列表理解,以避免创建无意义的中间列表。 – ShadowRanger 2015-10-19 13:48:56