python - python 2.6 vr 中的列表理解和 lambda 表达式。 python 2.7

标签 python python-2.6

我正在尝试将为 python 2.7 编写的代码反向移植到 python 2.6(原因是应该运行代码的服务器只有 python 2.6,而管理员拒绝安装 python 2.7 或更高版本)。

总的来说这很好用,但我发现了以下问题。在原始代码中,行(或类似的东西):

g = lambda x : ['{:d}'.format(i) for i in x]
g([1,2,3,4])

工作正常。但是,在 python 2.6 中它们会产生错误。我在文档中找不到关于此主题的任何内容。

这是什么原因?这个问题是否有任何简单的解决方案,即等效(相同语义)但使用不同语法的 lambda 表达式的定义?

最佳答案

在 Python 2.6 中,字段名称是必需的(参见 Format String Syntax )。在 Python 2.7+ 中,it can be omitted :

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

所以如果你想让你的代码兼容Python 2.6,那么这样写:

g = lambda x : ['{0:d}'.format(i) for i in x]
g([1,2,3,4])

关于python - python 2.6 vr 中的列表理解和 lambda 表达式。 python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112511/

相关文章:

python - SQLAlchemy 关系错误 : object has no attribute 'c'

python - fd.seek() IOError : [Errno 22] Invalid argument

python - 十六进制和其他一些字符串的正则表达式

python - 类型错误 : unhashable type: list when using Python set of strings

python - 如何在 Python 3.3 中引发异常

python - 在 Django 模型中将字段命名为 'id' 是否安全?

user-interface - 取消选择单选按钮

python - 为什么 pandas dataframe describe().min 方法返回标准偏差?

python - 如何比较嵌套字典值的日期

Python 2.6 - 解析参数