-1
import re
from collections import Counter

words = re.findall('\w+', open('/Users/Jack/Desktop/testytext').read().lower())

listy = Counter(words).most_common()


theNewList = list(listy)


theNewList[1][1] = 10

#****ERROR HERE****
#Traceback (most recent call last):
# File "countTheWords.py", line 16, in <module>
#    theNewList[1][1] = 10
#TypeError: 'tuple' object does not support item assignment

私の考えでは、list() 呼び出しは「listy」をリストに変換する必要があります。私が間違っていることは何ですか?

4

3 に答える 3

2

listy list: _

>>> type(listy)
<type 'list'>

その要素は次のとおりです。

>>> type(listy[1])
<type 'tuple'>

そして、それらの要素の1つを変更しようとしています:

>>> type(listy[1][1])
<type 'int'>

次のように要素を変換できます。

>>> listier = [list(e) for e in listy]
>>> type(listier)
<type 'list'>
>>> type(listier[1])
<type 'list'>
>>> type(listier[1][1])
<type 'int'>

そして、次を割り当てます。

>>> listier[1][1] = 10
>>> listier[1][1]
10
于 2013-10-16T05:32:44.557 に答える
1

.most_common()タプルのリストを返します。あなたがするときlist(listy)、あなたは実際には何も変えていません。内部のタプルをリストに変更しません。

タプルは不変であるため、その中の項目を変更することはできません (変更可能なリストと比較して)。

ただし、次を使用してそれらをリストに変更できますmap()

map(list, listy)
于 2013-10-16T05:30:45.177 に答える
0

theNewList[1]タプルを返す有効なリスト item-access です。したがってtheNewList[1][1] = 10、タプル項目に割り当てようとする試みです。タプルは不変であるため、これは無効です。

とにかく新しいカウントを割り当てたいのはなぜですか?

于 2013-10-16T05:30:36.880 に答える