Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要在代码中设置的Python更改列表_Python_Python 3.x - Fatal编程技术网

要在代码中设置的Python更改列表

要在代码中设置的Python更改列表,python,python-3.x,Python,Python 3.x,我正在寻找一个函数,该函数给定一个stringlist,我从其中的单词行中获取单词和索引: 范例 s = ['this is the first document', 'this is the second document', 'and this is a third document', 'perhaps there should be a fourth document', 'and now there is a fifth too'] 当我应用我的函数时 def makeInverse

我正在寻找一个函数,该函数给定一个stringlist,我从其中的单词行中获取单词和索引:

范例

s = ['this is the first document',
'this is the second document',
'and this is a third document',
'perhaps there should be a fourth document',
'and now there is a fifth too']
当我应用我的函数时

def makeInverseIndex(s):

    dic={}
    index=0
    for line in s:
        set=line.split()
        for palabra in set:
            if palabra in dic:
                dic[palabra]=dic[palabra]+[index]
            else:
                dic[palabra]=[index]
        index+=1


    return dic
我正在获得

{'a': [2, 3, 4], 'first': [0], 'the': [0, 1], 'and': [2, 4], 'there': [3, 4], 'perhaps': [3], 'document': [0, 1, 2, 3], 'should': [3], 'is': [0, 1, 2, 4], 'be': [3], 'fourth': [3], 'third': [2], 'second': [1], 'too': [4], 'fifth': [4], 'now': [4], 'this': [0, 1, 2]}
但我想获得

{'a': {2, 3, 4}, 'first': {0}, 'the': {0, 1}, 'and': {2, 4}, 'there': {3, 4}, 'perhaps': {3}, 'document': {0, 1, 2, 3}, 'should': {3}, 'is': {0, 1, 2, 4}, 'be': {3}, 'fourth': {3}, 'third': {2}, 'second': {1}, 'too': {4}, 'fifth': {4}, 'now': {4}, 'this': {0, 1, 2}}
我必须在代码中更改什么?我已经读到了列表和集合之间的区别,我正在使用集合来获取{},但是它不起作用


谢谢大家

使用
dict.setdefault

def makeInverseIndex(s):
    dic={}
    for index, line in enumerate(s):  #use enumerate() for getting index as well as item
        words = line.split()
        for palabra in words:
            dic.setdefault(palabra,set()).add(index)

不要使用
set
作为变量名,因为它隐藏了内置函数
set()

您“使用set”是什么意思?仅仅调用某个
set
与创建
set
类型的对象是非常不同的!对不起,我的英语不好,我的意思是我的输出必须是一个字典,它将任何文档中的每个单词映射到包含该单词的所有文档的文档ID(即strlist中的索引)组成的集合。输出仍然是相同的:$@TomeuOliverArbona这是不可能的,顺便说一句语法
{1,2}
for set是在py3.x中引入的,所以如果您使用的是py2.x,那么您将看到类似于
set([1,2])
的内容。非常感谢,也许对我来说,因为使用Shell,一切都很糟糕,所以我没有工作。谢谢,我应该使用哪个程序来使用python而不是python 3.3.2 Idle?Thanks@Zipp对于运行脚本,有许多IDE可用,如geany、eclipse、pycharm等。对于交互式shell,我建议使用IPython shell。