3

Looking for a way to transform a list of coordinates into pairs of dictionaries, i.e if:

l = [1, 2, 3, 4, 5, 6, 7, 8]

I want to create a list of dictionaries:

output = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, ... ]

Any ideas on how to do this "pythonically"?

4

5 回答 5

10

典型的方法是使用“石斑鱼”配方:

from itertools import izip
def grouper(iterable,n):
    return izip(*[iter(iterable)]*n)

output = [{'x':a,'y':b} for a,b in grouper(l,2)]

这里的优点是它可以与任何可迭代的 . iterable 不需要是可索引的或类似的东西......

于 2013-05-16T23:18:13.943 回答
6
output = [{'x': l[i], 'y': l[i+1]} for i in range(0, len(l), 2)]

或者:

output = [{'x': x, 'y': y} for x, y in zip(*[iter(l)]*2)]

这种从列表中对项目进行分组的方法直接来自zip()文档

于 2013-05-16T23:16:49.580 回答
4

你可以做:

>>> mylist = [1,2,3,4,5,6,7,8]
>>> [{'x': x, 'y': y} for x, y in zip(mylist[::2], mylist[1::2])]
[{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]

请注意,字典是无序{'y': 2, 'x': 1}的,因此与{'x': 1, 'y': 2}. 这利用了 Python 的内置zip()函数。

于 2013-05-16T23:18:05.153 回答
2

我相信 anamedtuple比字典更适合这份工作。(使用像@mgilson这样的itertools石斑鱼食谱)

>>> from collections import namedtuple
>>> from itertools import izip
>>> Point = namedtuple('Point', ('x', 'y'))
>>> def grouper(iterable,n):
        return izip(*[iter(iterable)]*n)

>>> nums = [1, 2, 3, 4, 5, 6, 7, 8]
>>> [Point(x, y) for x, y in grouper(nums, 2)]
[Point(x=1, y=2), Point(x=3, y=4), Point(x=5, y=6), Point(x=7, y=8)]
于 2013-05-17T01:26:54.090 回答
2

这是另一种方式

>>> from itertools import izip
>>> l = [1, 2, 3, 4, 5, 6, 7, 8]
>>> l = iter(l)
>>> [dict(x=x, y=y) for (x, y) in izip(l, l)]                                   
[{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]

或者,正如 Lattyware 建议的那样

 >>> [{'x':x, 'y':y} for (x, y) in izip(l, l)]
 [{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]
于 2013-05-16T23:32:49.863 回答