Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

333
Views
¿Cómo puedo tomar entradas separadas por comas para el módulo python AnyTree?

comunidad Necesito aceptar múltiples entradas separadas por comas para producir un resumen de información (específicamente, ¿cuántos empleados diferentes participaron en cada grupo/proyecto)? El programa toma empleados, gerentes y grupos en forma de cadenas.

Estoy usando la biblioteca anytree python para poder buscar/contar la ocurrencia de cada empleado por grupo. Sin embargo, este programa solo acepta un valor/celda a la vez en lugar de múltiples valores.

Aquí está la estructura de árbol y cómo acepto los valores de entrada.

 Press q to exit, Enter your data: Joe Press q to exit, Enter your data: Manager1 Press q to exit, Enter your data: Group1 Press q to exit, Enter your data: Charles Press q to exit, Enter your data: Manager1 Press q to exit, Enter your data: Group2 Press q to exit, Enter your data: Joe Press q to exit, Enter your data: Manager3 Press q to exit, Enter your data: Group1 Press q to exit, Enter your data: Charles Press q to exit, Enter your data: Manager3 Press q to exit, Enter your data: Group1 Press q to exit, Enter your data: Joe Press q to exit, Enter your data: Manager5 Press q to exit, Enter your data: Group2 Press q to exit, Enter your data: q Employee No of groups JOE 2 CHARLES 2 Group ├── GROUP1 │ ├── JOE │ │ └── MANAGER1 │ ├── JOE │ │ └── MANAGER3 │ └── CHARLES │ └── MANAGER3 └── GROUP2 ├── CHARLES │ └── MANAGER1 └── JOE └── MANAGER5

Necesito ayuda con este código para que pueda aceptar valores separados por comas; por ejemplo, para ingresar Joe, Manager1, Group1 a la vez.

 import anytree from anytree import Node, RenderTree, LevelOrderIter, LevelOrderGroupIter, PreOrderIter import sys # user input io='' lst_input = [] while (io!='q'): io=input('Press q to exit, Enter your data: ') if io!='q': lst_input.append(io.upper()) # change list in to matrix lst=[] for i in range(0, len(lst_input), 3): lst.append(lst_input[i:i + 3]) lst # create tree structure from lst group = Node('Group') storeGroup = {} for i in range(len(lst)): if lst[i][2] in [x.name for x in group.children]: # parent already exist, append childrens storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]]) storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]]) else: # create parent and append childreds storeGroup[lst[i][2]] = Node(lst[i][2], parent=group) storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]]) storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]]) store = {} for children in LevelOrderIter(group, maxlevel=3): if children.parent!=None and children.parent.name!='Group': if children.name not in store: store[children.name] = {children.parent.name} else: store[children.name] = store[children.name] | {children.parent.name} print('Employee', ' No of groups') for i in store: print(' '+i+' ', len(store[i])) for pre,fill, node in RenderTree(group): print('{}{}'.format(pre,node.name))


¡Gracias! Cualquier pensamiento es bienvenido.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Creo que una forma de hacerlo es:

 name, role, grp = io.upper().split(',')

que para una entrada como Joe, Manager1, Group1

 Python 3.7.9 (v3.7.9:13c94747c7, Aug 15 2020, 01:31:08) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> name, role, grp = input("Press q to exit, Enter your data:").split(",") Press q to exit, Enter your data:Joe, Manager1, Group1 >>> name 'Joe' >>> role ' Manager1' >>> grp ' Group1'

Eso funcionaría para ti ?

over 4 years ago · Santiago Trujillo Report

0

Aproveche el desempaquetado para extraer elementos. Entonces la sentencia if se puede reescribir de esta manera.

 if io!='q': name, role, grp = io.upper(). split(',') lst_input.append([name,role, grp])

también necesita cambiar lst.append(lst_input[i:i + 3]) en el bucle for a esto.

 lst.append(lst_input[0][i:i + 3])
over 4 years ago · Santiago Trujillo Report

0

Su salida lst es algo como:

 [['Joe', 'Manager1', 'Group1'], ['Charles', 'Manager1', 'Group2'], ['Joe', 'Manager3', 'Group1'], ['Charles', 'Manager3', 'Group1'], ['Joe', 'Manager5', 'Group2']]

El siguiente código genera la misma salida lst con un rendimiento mucho mejor:

 import anytree from anytree import Node, RenderTree, LevelOrderIter, LevelOrderGroupIter, PreOrderIter import sys # user input lst = [] while True: io=input('Press q to exit, Enter your data: ') if io!='q': lst.append(io.upper().split(',')) else: break print(lst) # create tree structure from lst group = Node('Group') storeGroup = {} for i in range(len(lst)): if lst[i][2] in [x.name for x in group.children]: # parent already exist, append childrens storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]]) storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]]) else: # create parent and append childreds storeGroup[lst[i][2]] = Node(lst[i][2], parent=group) storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]]) storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]]) store = {} for children in LevelOrderIter(group, maxlevel=3): if children.parent!=None and children.parent.name!='Group': if children.name not in store: store[children.name] = {children.parent.name} else: store[children.name] = store[children.name] | {children.parent.name} print('Employee', ' No of groups') for i in store: print(' '+i+' ', len(store[i])) for pre,fill, node in RenderTree(group): print('{}{}'.format(pre,node.name))

Definir muchas listas innecesarias en su código original arruinará su rendimiento. Incluso evite hacer la comparación adicional o definir variables innecesarias. Tenga en cuenta que no tenemos estructura do ... while en Python . Entonces, usamos break para evitar hacer comparaciones duplicadas.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!