我想更改由findall()函数返回的元组列表中的内容。而且我不确定我是否可以将元素从字符串更改为整数。而错误总是表明我需要超过1个值。
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
答案 0 :(得分:2)
问题在于for posts, comments in tuples:
行。这里tuples
实际上是一个包含两个字符串的元组,因此不需要迭代它。你可能想要这样的东西:
matches = re.findall(...)
for posts, comments in matches:
....
答案 1 :(得分: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))
从字符串到整数的转换很好。