有趣的是我还想出了其他方法。
>>> from collections import OrderedDict as OD
>>> attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))
如果你想反转,你可以这样做
>>> reverse = OD(attributes.items()[::-1])
或者更pythonic的方法:
>>> 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]))
或更多pythonic:
>>> 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
您可以结合使用这两种方法来反转和反转。
这行得通,但是效率低吗?通过使用 reversed(list(a.items())) 这会产生很多开销,所以不是 pythonic 吗?倒置属性也一样。
有些东西可能会产生很多开销并且是 Python 的,另一方面,有些东西可能非常非常有效但不是很 Python,这个词有点被滥用了,但这只是我的看法
来自维基百科:
Python 社区中一个常见的新词是 pythonic,它可以具有与程序风格相关的广泛含义。说代码是 Pythonic 就是说它很好地使用了 Python 习语,它是自然的或表现出对语言的流利程度。同样,说一个接口或语言特性是 Pythonic 就是说它可以很好地与 Python 习语配合使用,它的使用与该语言的其余部分很好地结合。
相比之下,非 Python 代码的一个标志是它试图用 Python 编写 C++(或 Lisp、Perl 或 Java)代码——也就是说,提供粗略的转录,而不是从另一种语言的形式的惯用翻译。 pythonicity 的概念与 Python 的可读性极简主义哲学紧密相连,并避免了“有不止一种方法可以做到这一点”的方法。不可读的代码或难以理解的习语是不合 Python 的。
至于:
但是随着我们扩大规模,这会降低性能吗?
这很难说,不知道您为什么要进行此类转换,也不知道它们是否是您系统的一个组成部分,从根本上讲,它们会增加线性时间/空间开销,这可能是好的,也可能不是好的,如果条目的数量仍然很少,那么没问题,但是如果在每个请求中,假设这发生在 Web 服务器上,您正在对大型 dicts 执行此操作,这可能非常苛刻,可能需要重新设计以避免这种情况。