ValueError: 需要更多的值进行解包

1 投票
2 回答
4401 浏览
提问于 2025-04-17 02:13

我想要修改一个由findall()函数返回的元组列表里的内容。但是我不确定能不能像这样把里面的字符串转换成整数。而且总是出现错误,提示我需要多个值。

Ntuple=[]

match = re.findall(r'AnswerCount="(\d+)"\s*CommentCount="(\d+)"', x)

print match

for tuples in match:
    for posts, comments in tuples:
        posts, comments = int(posts), (int(posts)+int(comments))  ## <- error

print match

2 个回答

1

match 是一个包含多个元组的列表。正确的遍历方式是:

  matches = re.findall(r'AnswerCount="(\d+)"\s*CommentCount="(\d+)"', x)
  for posts, comments in matches:
    posts, comments = int(posts), (int(posts)+int(comments))

把字符串转换成整数的方式是没问题的。

2

问题出在这一行 for posts, comments in tuples:。这里的 tuples 实际上是一个包含两个字符串的单一元组,所以其实不需要去循环它。你可能想要的是这样的:

matches = re.findall(...)
for posts, comments in matches:
    ....

撰写回答