2014-04-13 163 views
-1

我有一个人名单和谁控制谁,但我需要将他们全部结合起来,并形成几个句子来计算哪个人控制一个人的名单。在Python中创建词典

雇员顺序来自一个txt文件:

一个控件b
一个控制ç
一个控件D
B控制Ç
d照样E
d控制f
ë控制f

我知道我必须创建一个将txt文件加载到其中的字典,但我是stuc ķ。 关于如何做到这一点的任何想法?

+3

任何尝试完成? – Christian

+2

这和你的[上一个问题](http://stackoverflow.com/questions/22980434/creating-dictionaries-to-list-order-of-ranking)是一样的吗? – DSM

回答

1
  • 逐行读取文件。
  • 将每行的第一个和最后一个单词解压缩为列表中的元组。
  • 处理这个列表和内容创建字典

    afile = open('filename') 
    tuple_data = [] 
    for line in afile: 
        a = line.strip().split() 
        tuple_data.append((a[0].strip(), a[-1].strip())) 
    

tuple_data现在有:

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('d', 'e'), ('d', 'f'), ('e', 'f')] 

现在使用defaultdict构建输出:

>>> from collections import defaultdict 
>>> output = defaultdict(list) 
>>> for x, y in tuple_data: 
...  output[x].append(y) 
... 
>>> output 
defaultdict(<class 'list'>, {'a': ['b', 'c', 'd'], 'b': ['c'], 'e': ['f'], 'd': ['e', 'f']}) 

现在你可以打印输出为:

print 'Employee order:' 
for k, v in output.items(): 
    values = ','.join(v) 
    print '\t{} controls {}'.format(k, values) 
+0

我将如何让它,所以每个最后的值有一个“和”之前,而不是一个“,”,如果我想用任何不同的文本,我想我会改变它afile =打开(输入('文件名' )) – user3467226