将python中的单个有序列表转换为字典,蟒蛇 [英] Converting a single ordered list in python to a dictionary, pythonically
问题描述
我似乎找不到从 t 开始的优雅方式,并导致 。
I can't seem to find an elegant way to start from t and result in s.
>>>t = ['a',2,'b',3,'c',4]
#magic
>>>print s
{'a': 2, 'c': 4, 'b': 3}
解决方案我已经提出似乎不那么优雅:
Solutions I've come up with that seems less than elegant :
s = dict()
for i in xrange(0, len(t),2): s[t[i]]=t[i+1]
# or something fancy with slices that I haven't figured out yet
显然很容易解决,但是再次,似乎有一个更好的方法。有没有?
It's obviously easily solved, but, again, it seems like there's a better way. Is there?
推荐答案
我会使用 itertools
,但如果你认为这很复杂(就像你在评论中暗示的那样),那么可能:
I'd use itertools
, but, if you think that's complicated (as you've hinted in a comment), then maybe:
def twobytwo(t):
it = iter(t)
for x in it:
yield x, next(it)
d = dict(twobytwo(t))
或者等价于,再次返回到itertools,
or equivalently, and back to itertools again,
def twobytwo(t):
a, b = itertools.tee(iter(t))
next(b)
return itertools.izip(a, b)
d = dict(twobytwo(t))
或者,如果你坚持在一个季节适当的伎俩或对待的心情:
or, if you insist on being inline, in a season-appropriate "trick or treat" mood:
d = dict((x, next(it)) for it in (iter(t),) for x in it)
我,我认为这个一个伎俩,但有些人可能会发现它是一种治疗。 IOW,我发现这样的事情是可怕的,但显然在美国,在这几年的这段时间里,这些东西应该是成为; - )。
me, I consider this a trick, but some might find it a treat. IOW, I find this kind of thing scary, but apparently in the US around this time of the years things are supposed to be;-).
基本上,问题归结为我如何一次列出2个项目,因为 dict
非常乐意采取一系列的2元组和把它变成字典。我在这里显示的所有解决方案确保只有 O(1)
需要额外的空间(超出空间,显然 O(N)
,这是输入列表和输出命令所必需的,当然)。
Basically, the problem boils down to "how do I walk a list 2 items at a time", because dict
is quite happy to take a sequence of 2-tuples and make it into a dictionary. All the solutions I'm showing here ensure only O(1)
extra space is taken (beyond the space, obviously O(N)
, that's needed for the input list and the output dict, of course).
The suggested approach in the docs (everybody should be familiar with that page, the itertool recipes) is the function pairwise
on that page, which is basically the second one I suggested here. I do think every site-packages directory should contain an iterutils.py
file with those recipes (pity such a file's not already a part of python's stdlib!-).
这篇关于将python中的单个有序列表转换为字典,蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!