-1

I am trying to WRITE A FUNCTION to change the every instance in a list of tuples. Basically i need to convert the every instance of the list from ('value', number, 'value') to Arc('value', number, 'value')

Input:   [('root', 1, 'a'), ('b', 0.0, 'root'), ('b', 2, 'c'), ('a', 5, 'd'), ('b', 7, 'a')]

def Convert(t):
    t1=('head', 'weight', 'tail')
    t2=namedtuple('Arc', (t1))
    return t2

Required Output: [Arc('root', 1, 'a'), Arc('b', 0.0, 'root'), Arc('b', 2, 'c'), Arc('a', 5, 'd'), Arc('b', 7, 'a')]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Your `Convert` function is literally 4 characters away from doing exactly what you need with a single entry. Please explain where exactly you're stuck. – ForceBru Aug 19 '19 at 09:54
  • i need to change the elements of the tuple list [('root', 1, 'a'), ('b', 0.0, 'root'), ('b', 2, 'c'), ('a', 5, 'd'), ('b', 7, 'a')] as required output and i need my function to work for any provide input of the given form. – Asiis Pradhan Aug 19 '19 at 11:09

1 Answers1

0

You can use list-comprehension to convert your list of tuples to list of named-tuples:

t = [ ('root', 1, 'a'), ('b', 0.0, 'root'), ('b', 2, 'c'), ('a', 5, 'd'), ('b', 7, 'a') ]

from collections import namedtuple

Arc = namedtuple('Arc', 'head weight tail')

def Convert(t):
    return [Arc(*item) for item in t]

print(Convert(t))

Prints:

[Arc(head='root', weight=1, tail='a'), Arc(head='b', weight=0.0, tail='root'), Arc(head='b', weight=2, tail='c'), Arc(head='a', weight=5, tail='d'), Arc(head='b', weight=7, tail='a')]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91