且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将python中的单个有序列表转换为字典,蟒蛇

更新时间:2022-12-05 15:28:51

我会使用 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).

建议的方法在(每个人都应该熟悉该页面,itertool食谱)是函数成对的,这基本上是我在这里建议的第二个。我确实认为每个site-packages目录应该包含一个 iterutils.py 文件与这些食谱(可惜这样的文件不是python的stdlib的一部分!)。

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!-).