2011-09-13 59 views
1

我想更改由findall()函数返回的元组列表中的内容。而且我不确定是否可以像这样将字符串中的元素更改为整数。而错误总是表明我需要超过1个值。ValueError:需要多个值才能解压

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

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

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

@ interjay:是的,谢谢。我认为列表的元素是元组,而元组的元素是两个'posts'和'comments',因此我写了两个for循环。看起来,单个元组不能在for循环中进行迭代。这就是它出现错误的原因。我对么? :) – AnneS

+0

@ user942891:您可以遍历一个元组,但是一次只能得到一个字符串。你在这里想要的是同时获得两个字符串,以便你可以将它们分配给'posts'和'comments'变量。当你像这样分配了多个变量时,元组将自动解包,所以不需要迭代它。 – interjay

+0

@ interjay:谢谢。这一次,我明白了。而且更多的是,我仍然在分配上遇到问题。为什么'posts,comments = int(posts),(int(posts)+ int(comments))'根本没有改变元组列表?我非常感谢你的帮助。 :) – AnneS

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

从字符串到整数的转换很好。

+0

'在match'元组是正确的,因为比赛是re.findall'的'的返回值(即列表)。虽然它被混淆命名。 – interjay

+0

@interjay:是的,谢谢你,更正。 – NPE

+0

是的,这一次没有错误出现。但是当我打印新的匹配来查看元组的变化时,它仍然保持不变。为什么我的元组任务没有工作? – AnneS

相关问题