You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则匹配元组转字典触发ValueError:元素长度需为2但实际为6

解决dict(m.groups())触发的ValueError问题

嘿,这个问题我太熟悉啦!咱们先搞清楚错误根源,再一步步修复。

为什么会报错?

当你调用m.groups()时,它返回的是一个二元组(比如('Point1', '1.983990908e+00 ...')),但dict()函数的要求是传入键值对的序列——也就是包含多个二元组的列表,比如[(key1, val1), (key2, val2)]。

如果你直接把单个二元组丢给dict(),Python会把第一个元素(比如'Point1')拆成单个字符当键,第二个元素拆成单个字符当值,这完全不是你想要的逻辑,自然会抛出长度不匹配的错误。

修复方案(附优化后的完整代码)

同时还要注意:你需要把所有Point对象都存到同一个字典里,而不是每次循环都新建字典。这里给你两种简洁的修复方式:

方案1:把二元组包装成列表后更新字典

import re as re
n = nuke.selectedNode()
k = n.knob('scene')
script = k.toScript().replace('\n','').split('scenegraph {')

# 初始化空字典,用来存所有Point的键值对
point_dict = {}

for sgrph in script:
    # 去掉不必要的外层循环,直接接收匹配结果
    m = re.match(r".*\bname '([Point\d]+)'.*\btransform ([0-9.e+\- ]+)", sgrph)
    if m is not None:
        print(m.groups())
        # 把二元组包装成列表,再更新到字典
        point_dict.update([m.groups()])
        print(".........")
        print(point_dict)

方案2:直接通过分组索引赋值(更直观)

import re as re
n = nuke.selectedNode()
k = n.knob('scene')
script = k.toScript().replace('\n','').split('scenegraph {')

point_dict = {}

for sgrph in script:
    m = re.match(r".*\bname '([Point\d]+)'.*\btransform ([0-9.e+\- ]+)", sgrph)
    if m is not None:
        print(m.groups())
        # 直接用group(1)取键,group(2)取值
        point_dict[m.group(1)] = m.group(2)
        print(".........")
        print(point_dict)

另外提一句:你之前代码里的for m in [re.match(...)]是多余的,直接把匹配结果赋值给m就好,这样代码更简洁~

内容的提问来源于stack exchange,提问作者J. doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:35:28