【问题标题】:Creating a set in dictionary在字典中创建集合
【发布时间】:2014-02-21 18:02:32
【问题描述】:

我需要在字典中创建一个集合。

dicInvertedIndex = {}
docID = 1

for i in string:
  if condition:
    docID += 1
  dicInvertedIndex[i] = [1, set(docID)]

我有一个错误:

dicInvertedIndex[i] = [1, set(docID)]
 TypeError: 'int' object is not iterable

在我尝试这个之前,我在字典中创建了一个列表并且它有效。

dicInvertedIndex[i] = [ 1 , [ docID ] ]

而且它有效。我需要用我的文档的键和 (int, set()) 的值创建一个字典

点赞dic["awake"] = [5, {2, 30, 99, 234}]

本来我用的是list,但是速度很慢,我想用set。

【问题讨论】:

  • not iterable 听起来像是for 循环。仔细检查 string 中的内容。
  • 您应该询问如何解决您的基本问题,而不是为什么您尝试的解决方案不起作用。
  • 好的,谢谢。我问另一个问题

标签: python linux windows dictionary set


【解决方案1】:

set() 构造函数采用可迭代对象。 docID 是一个整数,因此不可迭代。

两种解决方法是

{docID} 

set([docID])

【讨论】:

    【解决方案2】:

    set() 的参数预计是可迭代的,只需在传递时将 docID 放入列表中即可:

    dicInvertedIndex[i] = [1, set([docID])]
    

    【讨论】:

    • 谢谢。有没有更适合我使用的存储结构。我需要一个符号频率(计数)以及在哪里相遇
    【解决方案3】:

    我不知道您要完成什么,但我看到了您的错误。 set 构造函数需要一个可迭代对象,并且您传递的是一个整数。这是修复:

    dicInvertedIndex[i] = [1, set([docID])]
    

    请注意 docID 在方括号内。

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 2015-01-30
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多