python无法获得dictionary的正确输出

2024-04-26 21:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

文件包含以下字符串:

I have no pride     
I have no shame   
You gotta make it rain    
Make it rain rain rain

输出应如下所示:

 {'rain': [2, 3], 'gotta': [2], 'make': [2], 'it': [2, 3], 'shame': [1], 'I': [0, 1], 'You': [2], 'have': [0, 1], 'no': [0, 1], 'Make': [3], 'pride': [0]}

但我明白了:

{'I': 1, 'have': 1, 'gotta': 2, 'Make': 3, 'it': 3, 'rain': 3, 'You':
 2, 'no': 1, 'make': 2, 'shame': 1, 'pride': 0}

我的代码:

def lineIndex(fName):
    fileName=open(fName)
    contents=fileName.readlines()
    fileName.close()
    d={}
    lst=[]
    count=-1
    for line in  contents:
        if line not in lst:
            print(line)
            lst.append(line)
            count+=1

        t=line.split()
        y2=[]    
        for eachWord in t:
            #print(eachWord)
            if eachWord not in d:
                y2.append(eachWord)
                d[eachWord]=count
            if eachWord in d:
                d[eachWord]=count

    return d

Tags: noinyoumakehavecountlineit
3条回答

问题在于:

y2=[]
for eachWord in t:
    #print(eachWord)
    if eachWord not in d:
        y2.append(eachWord)
        d[eachWord]=count
    if eachWord in d:
        d[eachWord]=count

您不断地将每个键的值重置为最新的行号。相反,请尝试使用collections.defaultdict使每个值在默认情况下以列表开头,并枚举行以获取计数:

import collections

def lineIndex(fName):
    d = collections.defaultdict(list)
    with open(fName) as f:
        for idx,line in enumerate(f):
            for word in set(line.split()):
                d[word].append(idx)
    return d

这应该适合您:

from collections import defaultdict
with open('your_file.txt','r') as f:
    result = defaultdict(set)
    counter =0
    for line in f:
        for item in line.split():
            result[item].add(counter)
        counter +=1
    print {i[0]:list(i[1]) for i in result.items()}

输出:

{'no': [0, 1], 'I': [0, 1], 'gotta': [2], 'it': [2, 3], 'rain': [2, 3], 
'shame': [1], 'have': [0, 1], 'You': [2], 'pride': [0], 'Make': [3], 'make': [2]}

没有任何导入模块的替代解决方案:

d = {}
with open("rain.txt") as f:
    for i,line in enumerate(f.readlines()):
        for word in line.split():
            if word in d:
                if i not in d[word]:
                    d[word].append(i)
            else:
                d[word] = [i]
print(d)                

结果如下:

{'no': [0, 1], 'gotta': [2], 'make': [2], 'rain': [2, 3], 'I': [0, 1], 
'You': [2], 'Make': [3], 'have': [0, 1], 'pride': [0], 'it': [2, 3], 
'shame': [1]}

不带枚举的备选方案:

d = {}
with open("rain.txt") as f:
    frl = f.readlines()
    for i in range(len(frl)):
        line=frl[i]
        for word in line.split():
            if word in d:
                if i not in d[word]:
                    d[word].append(i)
            else:
                d[word] = [i]
print(d)                

相关问题 更多 >