【问题标题】:Why is appending my list of tuples changing their content?为什么附加我的元组列表会改变它们的内容?
【发布时间】:2022-11-21 09:28:29
【问题描述】:

我正在尝试制作一个包含字符串和字典的元组列表。字符串是文件名,字典是 n-gram 的频率列表。

('story.txt',
 {'back': 12,
  'been': 13,
  'bees': 58,
  'buzz': 13,
  'cant': 30,
  'come': 12,
  'dont': 64,
  'down': 16,
  'from': 22,
   ...})

对于我正在做的事情,我想列出这些看起来像的元组

[('story.txt',
 {'back': 12,
  'been': 13,
  'bees': 58,
  'buzz': 13,
  'cant': 30,
  'come': 12,
  'dont': 64,
  'down': 16,
  'from': 22,
   ...}),
('great_expectations.txt',
 {'_he_': 12,
  'able': 32,
  'aged': 54,
  'aint': 56,
  'also': 34,
  'arms': 44,
  'away': 158,
  'baby': 23,
  ...})
]

我正在尝试使用以下代码来做到这一点:

documents = ['story.txt', 'great_expectations.txt']

outputs = []

for document in documents:
    doc_map = map_maker.make_map(document, 4, 10)
    list_tuple = (document, doc_map)
    # pprint.pprint(list_tuple)
    outputs.append(list_tuple) 
    # pprint.pprint(outputs)

出于某种原因,上面的代码在附加字典之前组合了字典中的数据,这样“story.txt”字典将包含最初与“great_expectations.txt”关联的条目,反之亦然,如下所示:

[('story.txt',
  {'_he_': 12,
   'able': 32,
   'aged': 54,
   'aint': 56,
   'also': 34,
   'arms': 44,
   'away': 158,
   'baby': 23,
   'back': 238,
   ...}),
('great_expectations.txt',
  {'_he_': 12,
   'able': 32,
   'aged': 54,
   'aint': 56,
   'also': 34,
   'arms': 44,
   'away': 158,
   'baby': 23,
   'back': 238,
   ...})
]

为什么要这样做?我认为元组应该是不可变的。

【问题讨论】:

  • map_maker.make_map() 函数在做什么?我会开始在那里搜索错误。

标签: python list dictionary n-gram


【解决方案1】:

您显示的代码没有问题,我推测您在map_maker.make_map 的某处留下了硬编码文件名,或者您重复使用了doc_map(它是静态的或类似的东西,请注意 python 中引用类型的默认参数)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2022-01-08
    • 2018-02-24
    相关资源
    最近更新 更多