创建字典列出排名顺序

创建字典列出排名顺序

本文介绍了创建字典列出排名顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人的列表,谁控制谁,但我需要结合它们,并形成几个句子来计算哪个人控制一个人的列表。

I have a list of people and who controls who but I need to combine them all and form several sentences to compute which person control a list of people.

员工订单来自 txt 文件:

推荐答案

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)

这篇关于创建字典列出排名顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:49