将值附加到元组

Appending values to a tuple

此代码将新值直接附加到元组。但是,元组应该是不可改变的。有人可以解释这里发生了什么吗?

word_frequency = [('hello', 1), ('my', 1), ('name', 2),
('is', 1), ('what', 1), ('?', 1)]

def frequency_to_words(word_frequency):
  frequency2words = {}
  for word, frequency in word_frequency:
    if frequency in frequency2words:
      frequency2words[frequency].append(word)
    else:
      frequency2words[frequency] = [word]
  return frequency2words

print(frequency_to_words(word_frequency))

结果:{1: ['hello', 'my', 'is', 'what', '?'], 2: ['name']}

这一行构成一个列表[]

frequency2words[frequency] = [word]

这就是你要 .append() 的目的。

但是你可以做 (1,2) + (3,4) 并且 Python 会创建一个更大的元组来容纳四个东西并将它们复制进去,使它看起来有效。你不能做的是改变 () 元组的内容:

>>> t = (1,2)
>>> t[0] = 5
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    t[0] = t
TypeError: 'tuple' object does not support item assignment

.append()操作是对frequency2words字典中的列表值进行的,不是word_frequency中的元组。

您可以使用 .setdefault() 重写您的代码以使其更简洁,这也应该让您更清楚地知道您要追加什么。

def frequency_to_words(word_frequency):
  frequency2words = {}
  for word, frequency in word_frequency:
      frequency2words.setdefault(frequency, []).append(word)
  return frequency2words