我想更改由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