我想更改由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
@ interjay:是的,谢谢。我认为列表的元素是元组,而元组的元素是两个'posts'和'comments',因此我写了两个for循环。看起来,单个元组不能在for循环中进行迭代。这就是它出现错误的原因。我对么? :) – AnneS
@ user942891:您可以遍历一个元组,但是一次只能得到一个字符串。你在这里想要的是同时获得两个字符串,以便你可以将它们分配给'posts'和'comments'变量。当你像这样分配了多个变量时,元组将自动解包,所以不需要迭代它。 – interjay
@ interjay:谢谢。这一次,我明白了。而且更多的是,我仍然在分配上遇到问题。为什么'posts,comments = int(posts),(int(posts)+ int(comments))'根本没有改变元组列表?我非常感谢你的帮助。 :) – AnneS