Invalid syntax using dict comprehension

Deadly 提交于 2019-12-17 14:56:11

问题


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?


回答1:


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:]))


来源:https://stackoverflow.com/questions/10933601/invalid-syntax-using-dict-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!