简体   繁体   English

Python array_flip 模拟或最好的方法来做到这一点?

[英]Python array_flip analogue or best way to do this?

Is there array_flip (php) analogue for Python 3.x?是否有适用于 Python 3.x 的 array_flip (php) 模拟?

from

obj = ['a', 'c', 'b' ]

to

{'a': 1, 'c':2, 'b': 3}

You can use a list comprehension along with the dict constructor, as follows:您可以将列表dictdict构造函数一起使用,如下所示:

>>> obj = [ 'a', 'c', 'b' ]
>>> dict((x, i + 1) for i, x in enumerate(obj))
{'a': 1, 'c': 2, 'b': 3}

As noted in the comments, you can also use a simple dict comprehension:如评论中所述,您还可以使用简单的 dict 理解:

>>> { x: i + 1 for i, x in enumerate(obj) }
{'a': 1, 'c': 2, 'b': 3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM