我想创建一个包含30个条目的命名元组,并使代码更短,我想做这样的事情:
from collections import namedtuple
header_dict = {0: "id",
1: "PR_DISPLAY_NAME",
2: "PR_HOME_ADDRESS_STREET",
3: "PR_ZIP",
...
29: "PR_SURNAME",
}
Person = namedtuple('Person', '{} {} {}'.format(header_dict[0], header_dict[1], header_dict[2]))
s = '{} ' * 30
Person = namedtuple('Person', s.format(header_dict[(i for i in range(30)]))
第一个“ Person = ...”指令有效,但是第二个指令产生:
KeyError: <generator object <genexpr> at 0x7fc2a1cff240>
我正在使用Python 3.4.2
代码应该是什么样子?还是有更好的方法来创建这个命名的元组?
答案 0 :(得分:1)
您可以使用值
In [1]: header_dict = {0: "id",
...: 1: "PR_DISPLAY_NAME",
...: 2: "PR_HOME_ADDRESS_STREET",
...: 3: "PR_ZIP",
...: 29: "PR_SURNAME",
...: }
...:
In [2]: s = '{} ' * len(header_dict)
In [3]: s.format(*header_dict.values())
Out[3]: 'id PR_DISPLAY_NAME PR_HOME_ADDRESS_STREET PR_ZIP PR_SURNAME '
您的代码将:
Person = namedtuple('Person',s.format(*header_dict.values()))
答案 1 :(得分:1)
您可以执行以下操作
Person = namedtuple('Person', s.format(*(header_dict[i] for i in range(30))))
从python 3.6开始,python dict保留插入顺序。因此,从python 3.6开始,您可以
Person = namedtuple('Person', ' '.join(header_dict.values()))