2011-09-13 57 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

相關問題