nbu*_*bis 3 python dictionary list
寻找一种将坐标列表转换为字典对的方法,即:
l = [1, 2, 3, 4, 5, 6, 7, 8]
Run Code Online (Sandbox Code Playgroud)
我想创建一个词典列表:
output = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, ... ]
Run Code Online (Sandbox Code Playgroud)
关于如何"蟒蛇"地做这个的任何想法?
mgi*_*son 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)]
Run Code Online (Sandbox Code Playgroud)
这里的优点是它可以与任何可迭代的一起使用.可迭代不需要是可索引的或类似的东西......
output = [{'x': l[i], 'y': l[i+1]} for i in range(0, len(l), 2)]
Run Code Online (Sandbox Code Playgroud)
或者:
output = [{'x': x, 'y': y} for x, y in zip(*[iter(l)]*2)]
Run Code Online (Sandbox Code Playgroud)
这种从列表中对项目进行分组的方法直接来自zip()文档.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |