更改元组的每个实例

Changing Every Instance of a tuple

我正在尝试编写一个函数来更改列表中的每个实例 元组。基本上我需要将列表的每个实例从 ('value', number, 'value') 转换为 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')]

您可以使用列表理解将元组列表转换为命名元组列表:

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))

打印:

[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')]