创建词典以列出排名顺序

时间:2014-04-10 06:43:31

标签: python list dictionary

我有一个人员列表,谁控制谁,但我需要将它们全部组合起来并形成几个句子来计算哪个人控制一个人列表。

员工订单来自txt文件:

1 个答案:

答案 0 :(得分:1)

from collections import defaultdict

controls = defaultdict(list)

with open('data.txt') as file:
    for line in file:
        controller, controlled = line.strip().split(' controls ')
        controls[controller].append(controlled)

print 'employee order:'
for controller, controlled in controls.iteritems():       
    if len(controlled) > 1:
        conjoined = ', '.join(controlled[:-1])
        conjoined = '{} and {}'.format(conjoined, controlled[-1])
    else:
        conjoined = controlled[0]
    print '{} controls {}'.format(controller, conjoined)