使用字典理解的语法无效 [英] Invalid syntax using dict comprehension

查看:36
本文介绍了使用字典理解的语法无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个名为x"的浮点数列表,我想创建一个字典,使用字典理解将 x[1:-1] 中的每个 x 映射到它的邻居.我尝试了以下行:

Given a list of floats named 'x', I would like to create a dict mapping each x in x[1:-1] to it's neighbors using a dict comprehension. I have tried the following line :

neighbours = {x1:(x0,x2) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:])}

但是,语法似乎无效.我做错了什么?

However, the syntax seems to be invalid. What am I doing wrong?

推荐答案

字典理解 仅在 Python 2.7 以上版本中可用.对于早期版本,您需要带有生成器的 dict() 构造函数:

Dict comprehensions are only available in Python 2.7 upwards. For earlier versions, you need the dict() constructor with a generator:

dict((x1, (x0,x2)) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:]))

这篇关于使用字典理解的语法无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆