将元素列表传递给命名元组

时间:2014-01-22 22:58:53

标签: python arguments namedtuple

我想创建一个namedtuple,其中有field_names。虽然它有太多field_names我创建了一个名为sub的列表,其中列出了field_names的项目列表。 result是我对namedtuple实例的引用。

sub = [
     'MA9221', 'MC9211', 'MC9212', 'MC9213', 'MC9214',
     'MC9215', 'MC9222', 'MC9223', 'MC9224', 'MC9225',
     'MC9231', 'MC9232', 'MC9233', 'MC9234', 'MC9235',
     'MC9241', 'MC9242', 'MC9243', 'MC9244', 'MC9251',
     'MC9252', 'MC9273', 'MC9277', 'MC9283', 'MC9285']
result = namedtuple('result', ['rollno', 'name'] + sub)

结果值:

rollno = 123123
name = "Sam"
sub_value = [
     1,0,0,0,0,
     0,0,1,1,1,
     1,1,1,0,0,
     1,1,0,0,1,
     1,1,1,0,1]

现在,我不知道如何将sub_value的元素传递给result(rollno, name, ...)

1 个答案:

答案 0 :(得分:3)

这一行实际上定义了类型本身:

result = namedtuple('result', ['rollno', 'name'] + sub)

要创建实例,您现在需要致电result(...)

>>> result(rollno, name, *sub_value)
result(rollno=123123, name='Sam', MA9221=1, MC9211=0, MC9212=0, MC9213=0, MC9214=0, MC9215=0, MC9222=0, MC9223=1, MC9224=1, MC9225=1, MC9231=1, MC9232=1, MC9233=1, MC9234=0, MC9235=0, MC9241=1, MC9242=1, MC9243=0, MC9244=0, MC9251=1, MC9252=1, MC9273=1, MC9277=1, MC9283=0, MC9285=1)