python - python 中的映射函数在解包值时抛出错误

标签 python python-2.7 dictionary list-comprehension

我正在尝试运行以下代码速度

punctDict = {'(':' ( ',')':' ) ','\t':'','\n':''}

for keys,value in map(re.escape, punctDict.keys(  )):
    print(keys,value)

它工作正常并给了我预期的输出

但是如果我尝试使用 punctDict = {'(':' ( ',')':' ) ','t':'','n':''}

上面的 for 循环抛出异常

ValueError: not enough values to unpack (expected 2, got 1)

最佳答案

问题在于您使用作为键,值来解压一个仅包含一个字符的字符串。观察两者之间的输出差异:

>>> punctDict = {'(':' ( ',')':' ) ','\t':'','\n':''}
>>> map(re.escape, punctDict.keys())
['\\)', '\\(', '\\\t', '\\\n']

还有这个:

>>> punctDict = {'(':' ( ',')':' ) ','t':'','n':''}
>>> map(re.escape, punctDict.keys())
['\\)', '\\(', 't', 'n']

请注意,在第二个示例中,'t' 和 'n' 只是变成了 't' 和 'n',并且单字符字符串无法使用逗号表示法解包。由于您只是 re.escape()-ing punctDict 的键,因此您不应期望在 for 循环中同时获取键和值。

您在此处运行的keys,value实际上并未访问punctDict的键和值re.escape() -d,而只是转义键并尝试分割字符串(并且成功,因为字符串只有 2 个字符。

如果您比较以下内容,您会看到相同的行为:

>>> firstPart, secondPart = 'xy'
>>> firstPart
'x'
>>> secondPart
'y'

这样:

>>> firstPart, secondPart = 'x'

Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    firstPart, secondPart = 'x'
ValueError: need more than 1 value to unpack

甚至这个:

>>> firstPart, secondPart = 'xyz'

Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    firstPart, secondPart = 'xyz'
ValueError: too many values to unpack

关于python - python 中的映射函数在解包值时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204336/

相关文章:

python - 为什么正则表达式在 Python 2.7 中匹配一个额外的空格?

javascript - 如何在 JavaScript/TypeScript 中创建具有非唯一键的 Map?

Android:语音识别追加字典?

python - Python中的单元测试

python - 给定 scipy.stats.binned_statistic 函数......如何使用不同大小的垃圾箱?

python - 如何在 python 脚本中使用 sudo su - 用户名并将密码传递给它

python - 使用复合返回语句对字典和列表的字典进行排序

python - 使用相似键和不同键的组合组合/合并字典

python - 如何自动识别同一篇论文的引用情况?

Python 使用 if 语句验证多个值