Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.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_Dictionary_Python 3.x - Fatal编程技术网

Python 循环字典值

Python 循环字典值,python,dictionary,python-3.x,Python,Dictionary,Python 3.x,我目前有一个程序,它读取一个文本文件,并根据里面的输入回答一组查询。这有助于查明被询问儿童的母亲是谁。我现在更进一步,重新处理提供的这些输出,以显示完整的族谱 这是一个文本文件,左侧包含父母,右侧包含孩子。下面是询问的问题,然后是输出 Sue: Chad, Brenda, Harris Charlotte: Tim Brenda: Freddy, Alice Alice: John, Dick, Harry mother Sue ancestors Harry ancestors Bernar

我目前有一个程序,它读取一个文本文件,并根据里面的输入回答一组查询。这有助于查明被询问儿童的母亲是谁。我现在更进一步,重新处理提供的这些输出,以显示完整的族谱

这是一个文本文件,左侧包含父母,右侧包含孩子。下面是询问的问题,然后是输出

Sue: Chad, Brenda, Harris
Charlotte: Tim
Brenda: Freddy, Alice
Alice: John, Dick, Harry

mother Sue
ancestors Harry
ancestors Bernard
ancestors Charlotte

>>> Mother not known
>>> Alice, Brenda, Sue
>>> Unknown Person
>>> No known ancestors
这个程序能够计算出母亲是谁(感谢Kampu的帮助),但我现在正试图理解如何获取这个值,并可能将其附加到一个新的列表或字典中,在那里无限循环以查找任何可能的祖父母

def lookup_ancestor(child):
    ancestor = REVERSE_MAP.get(child)
    if ancestor:
        ANCESTOR_LIST_ADD.append(ancestor)
    if ancestor not in LINES[0:]:
        print("Unknown person")
    else:
        print("No known ancestors")
这就是我到目前为止所做的,
REVERSE\u MAP
将每个孩子映射到字典中的父母。然后,我将这些父母放入一个新的列表中,我计划再次运行该列表,以确定他们的父母是谁。然而,我被困在这一点上,因为我找不到一种优雅的方式来执行整个过程,而不创建三个新列表来继续循环。目前的设置方式是,我假设我需要通过
for
循环附加它们,或者只是
split()
之后的值,以使所有值彼此保持一致。理想情况下,我想学习如何循环这个过程,并找出每个问题的祖先是谁

我觉得自己似乎已经掌握了它的可能外观,但我对Python的了解使我的尝试和错误方法无法达到时间效率

任何帮助都将不胜感激

编辑:链接-

编辑2:

def process_commands(commands, relation_dict):
    '''Processes the output'''
    output = []
    for c in commands: 
        coms = c.split()
        if len(coms) < 2: 
            output.append("Invalid Command")
            continue
        action = coms[0]
        param = coms[1]

def mother_lookup(action, param, relation_dict):
    output_a = []
    if action == "mother": 
        name_found = search_name(relation_dict, param)
        if not name_found: 
            output_a.append("Unknown person")
        else: 
            person = find_parent(relation_dict, param)
            if person is None: 
                output_a.append("Mother not known")
            else: 
                output_a.append(person)
    return output_a

def ancestor_lookup(action, param, relation_dict):
    output_b = []
    if action == "ancestors": 
        name_found = search_name(relation_dict, param)
        if not name_found: 
            output_b.append("Unknown person")
        else: 
            ancestor_list = []
            person = param
            while True: 
                person = find_parent(relation_dict, person)
                if person == None: 
                    break
                else: 
                    ancestor_list.append(person)
                if ancestor_list: 
                    output_b.append(", ".join(ancestor_list))
                else: 
                    output_b.append("No known ancestors")
    return output_b

def main():
    '''Definining the file and outputting it'''
    file_name = 'relationships.txt'
    relations,commands = read_file(file_name)
    #Process Relqations to form a dictionary of the type 
    #{parent: [child1,child2,...]}
    relation_dict = form_relation_dict(relations)
    #Now process commands in the file
    action = process_commands(commands, relation_dict)
    param = process_commands(commands, relation_dict)
    output_b = ancestor_lookup(action, param, relation_dict)
    output_a = mother_lookup(action, param, relation_dict)
    print('\n'.join(output_a))
    print ('\n'.join(output_b))


if __name__ == '__main__': 
    main()
def进程命令(命令、关系命令):
''处理输出''
输出=[]
对于命令中的c:
coms=c.split()
如果len(coms)<2:
append(“无效命令”)
持续
动作=通信量[0]
参数=coms[1]
定义母亲查找(操作、参数、关系):
输出_a=[]
如果操作==“母亲”:
name\u found=搜索名称(关系dict,参数)
如果未找到名称,\u:
输出附加(“未知人员”)
其他:
person=查找父项(关系dict,参数)
如果此人没有:
输出附加(“母亲不知道”)
其他:
输出追加(人)
返回输出_a
定义祖先查找(操作、参数、关系):
输出_b=[]
如果操作==“祖先”:
name\u found=搜索名称(关系dict,参数)
如果未找到名称,\u:
输出附加(“未知人员”)
其他:
祖先列表=[]
person=param
尽管如此:
person=查找父对象(关系,个人)
如果person==无:
打破
其他:
祖先列表。附加(个人)
如果您需要列表:
输出附加(“,”.join(祖先列表))
其他:
输出附加(“无已知祖先”)
返回输出
def main():
''定义文件并输出''
文件名='relationships.txt'
关系,命令=读取文件(文件名)
#处理关系以形成类型的字典
#{家长:[child1,child2,…]}
关系dict=形式关系dict(关系)
#现在处理文件中的命令
动作=处理命令(命令、关系命令)
param=过程命令(命令、关系命令)
输出=祖先查找(操作、参数、关系)
输出=母亲查找(操作、参数、关系)
打印('\n'.join(输出_a))
打印('\n'.连接(输出_b))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()

您使用祖先列表添加的方式表明,它的定义如下:

global ANCESTOR_LIST_ADD
ANCESTOR_LIST_ADD = []
如果是这种情况,并且祖先\u LIST\u ADD是全局的,您可以调用递归,它将填充祖先,直到出现以下情况:

def lookup_ancestor(child):
    ancestor = REVERSE_MAP.get(child)
    if ancestor:
        ANCESTOR_LIST_ADD.append(ancestor)
        lookup_ancestor(ancestor) #recursion
    if ancestor not in LINES:
        print("Unknown person")
    else:
        print("No known ancestors")
如果祖先列表添加是局部变量,则需要将其作为调用的一部分传递:

def lookup_ancestor(child, ANCESTOR_LIST_ADD):
    ancestor = REVERSE_MAP.get(child)
    if ancestor:
        ANCESTOR_LIST_ADD.append(ancestor)
        return lookup_ancestor(ancestor, ANCESTOR_LIST_ADD) #recursion
    if ancestor not in LINES:
        print("Unknown person")
    else:
        print("No known ancestors")
    return ANCESTOR_LIST_ADD

我还没有测试过它,但一般的想法是使用递归。

正如@NullUserException所说,树(或类似的东西)是一个不错的选择。 我发布的答案与您为这个问题选择的答案完全不同

可以定义一个Person对象,该对象知道其名称并跟踪其父对象。父对象不是名称,而是另一个人对象!(有点像链表)。然后,您可以将人员集合保留为单个列表

解析文件时,您会不断将人员添加到列表中,同时使用正确的对象更新其子/父属性

之后,对于任何人,只需打印属性以查找关系即可

下面是一个可能的实现(在Python-2.6上)。本例中的文本文件仅包含这些关系。查询稍后使用交互式输入触发

class Person(object): 
    """Information about a single name"""
    def __init__(self,name): 
        self.name = name
        self.parent = None
        self.children = []

def search_people(people,name): 
    """Searches for a name in known people and returns the corresponding Person object or None if not found"""
    try: 
        return filter(lambda y: y.name == name,people)[0]
    except IndexError: 
        return None

def search_add_and_return(people,name): 
    """Search for a name in list of people. If not found add to people. Return the Person object in either case"""
    old_name = search_people(people,name)
    if old_name is None: 
        #First time entry for the name
        old_name = Person(name)
        people.append(old_name)
    return old_name

def read_file(file_name,people): 
    fp = open(file_name,'r')
    while True: 
        l = fp.readline()
        l.strip('\n').strip()
        if not l: 
            break
        names = l.split(':')
        mother = names[0].strip()
        children = [x.strip() for x in names[1].split(',')]
        old_mother = search_add_and_return(people,mother)
        #Now get the children objects
        child_objects = []
        for child in children: 
            old_child = search_add_and_return(people,child)
            child_objects.append(old_child)
        #All children have been gathered. Link them up
        #Set parent in child and add child to parent's 'children'
        old_mother.children.extend(child_objects)
        for c in child_objects: 
            c.parent = old_mother
    fp.close()


def main(): 
    file_name = 'try.txt'
    people = []
    read_file(file_name,people)

    #Now lets define the language and start a loop
    while True: 
        command = raw_input("Enter your command or 0 to quit\n")
        if command == '0': 
            break
        coms = command.split()
        if len(coms) < 2: 
            print "Wrong Command"
            continue
        action = coms[0]
        param = coms[1]
        if action == "mother": 
            person = search_people(people,param)
            if person == None: 
                print "person not found"
                continue
            else: 
                if person.parent is None: 
                    print "mother not known"
                else: 
                    print person.parent.name
        elif action == "ancestors": 
            person = search_people(people,param)
            if person == None: 
                print "person not found"
                continue
            else: 
                ancestor_list = []
                #Need to keep looking up parent till we don't reach a dead end
                #And collect names of each ancestor
                while True: 
                    person = person.parent
                    if person is None: 
                        break
                    ancestor_list.append(person.name)
                if ancestor_list: 
                    print ",".join(ancestor_list)    
                else: 
                    print "No known ancestors"

if __name__ == '__main__': 
    main()
要查找父项,只需搜索名称是否在字典值中,如果找到,则返回键。如果没有找到母亲,则不返回任何母亲

mother = None
for k,v in relation_dict.items(): 
    if name in v: 
        mother = k
        break
return mother
如果你想找到所有的祖先,你只需要重复这个过程,直到没有返回

ancestor_list = []
person = name
while True: 
    person = find_parent(relation_dict,person)
    if person == None: 
        #Top of the ancestor chain found
        break
    else: 
        ancestor_list.append(person)
下面是Python-2.6中的一个实现。它假定文本文件的结构是这样的:首先是所有关系,然后是空行,然后是所有命令

def read_file(file_name): 
    fp = open(file_name,'r')
    relations = []
    commands = []
    reading_relations = True
    for l in fp: 
        l = l.strip('\n')
        if not l: 
            reading_relations = False
            continue
        if reading_relations:     
            relations.append(l.strip())
        else: 
            commands.append(l.strip())
    fp.close()
    return relations,commands

def form_relation_dict(relations): 
    relation_dict = {}
    for l in relations: 
        names = l.split(':')
        mother = names[0].strip()
        children = [x.strip() for x in names[1].split(',')]
        existing_children = relation_dict.get(mother,[])
        existing_children.extend(children)
        relation_dict[mother] = existing_children
    return relation_dict

def search_name(relation_dict,name): 
    #Returns True if name occurs anywhere in relation_dict
    #Else return False
    for k,v in relation_dict.items(): 
        if name ==k or name in v: 
            return True
    return False

def find_parent(relation_dict,param): 
    #Finds the parent of 'param' in relation_dict
    #Returns None if no mother found
    #Returns mother name otherwise
    mother = None
    for k,v in relation_dict.items(): 
        if param in v: 
            mother = k
            break
    return mother

def process_commands(commands,relation_dict): 
    output = []
    for c in commands: 
        coms = c.split()
        if len(coms) < 2: 
            output.append("Invalid Command")
            continue
        action = coms[0]
        param = coms[1]
        if action == "mother": 
            name_found = search_name(relation_dict,param)
            if not name_found: 
                output.append("person not found")
                continue
            else: 
                person = find_parent(relation_dict,param)
                if person is None: 
                    output.append("mother not known")
                else: 
                    output.append("mother - %s" %(person))
        elif action == "ancestors": 
            name_found = search_name(relation_dict,param)
            if not name_found: 
                output.append("person not found")
                continue
            else: 
                #Loop through to find the mother till dead - end (None) is not reached
                ancestor_list = []
                person = param
                while True: 
                    person = find_parent(relation_dict,person)
                    if person == None: 
                        #Top of the ancestor found
                        break
                    else: 
                        ancestor_list.append(person)
                if ancestor_list: 
                    output.append(",".join(ancestor_list))
                else: 
                    output.append("No known ancestors")
    return output

def main(): 
    file_name = 'try.txt'
    relations,commands = read_file(file_name)
    #Process Relqations to form a dictionary of the type {parent: [child1,child2,...]}
    relation_dict = form_relation_dict(relations)
    print relation_dict
    #Now process commands in the file
    output = process_commands(commands,relation_dict)
    print '\n'.join(output)


if __name__ == '__main__': 
    main()
EDIT2

如果您真的想将其进一步拆分为函数,下面是
process\u命令
的外观

def process_mother(relation_dict,name): 
    #Processes the mother command
    #Returns the ouput string
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found: 
        output_str = "person not found"
    else: 
        person = find_parent(relation_dict,name)
        if person is None: 
            output_str = "mother not known"
        else: 
            output_str = "mother - %s" %(person)
    return output_str

def process_ancestors(relation_dict,name): 
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found: 
        output_str = "person not found"
    else: 
        #Loop through to find the mother till dead - end (None) is not reached
        ancestor_list = []
        person = name
        while True: 
            person = find_parent(relation_dict,person)
            if person == None: 
                #Top of the ancestor found
                break
            else: 
                ancestor_list.append(person)
        if ancestor_list: 
            output_str = ",".join(ancestor_list)
        else: 
            output_str = "No known ancestors"
    return output_str

def process_commands(commands,relation_dict): 
    output = []
    for c in commands: 
        coms = c.split()
        if len(coms) < 2: 
            output.append("Invalid Command")
            continue
        action = coms[0]
        param = coms[1]
        if action == "mother": 
            new_output = process_mother(relation_dict,param)
        elif action == "ancestors": 
            new_output = process_ancestors(relation_dict,param)
        if new_output: 
            output.append(new_output)    
    return output
def进程(关系、名称):
#处理母命令
#返回输出字符串
输出_str=''
name\u found=搜索名称(关系、名称)
如果未找到名称,\u:
输出\u str=“未找到人员”
其他:
person=查找父对象(关系、名称)
如果此人没有:
输出
mother not known
Alice,Brenda,Sue
person not found
No known ancestors
def process_mother(relation_dict,name): 
    #Processes the mother command
    #Returns the ouput string
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found: 
        output_str = "person not found"
    else: 
        person = find_parent(relation_dict,name)
        if person is None: 
            output_str = "mother not known"
        else: 
            output_str = "mother - %s" %(person)
    return output_str

def process_ancestors(relation_dict,name): 
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found: 
        output_str = "person not found"
    else: 
        #Loop through to find the mother till dead - end (None) is not reached
        ancestor_list = []
        person = name
        while True: 
            person = find_parent(relation_dict,person)
            if person == None: 
                #Top of the ancestor found
                break
            else: 
                ancestor_list.append(person)
        if ancestor_list: 
            output_str = ",".join(ancestor_list)
        else: 
            output_str = "No known ancestors"
    return output_str

def process_commands(commands,relation_dict): 
    output = []
    for c in commands: 
        coms = c.split()
        if len(coms) < 2: 
            output.append("Invalid Command")
            continue
        action = coms[0]
        param = coms[1]
        if action == "mother": 
            new_output = process_mother(relation_dict,param)
        elif action == "ancestors": 
            new_output = process_ancestors(relation_dict,param)
        if new_output: 
            output.append(new_output)    
    return output