我正在编写一个代码,需要将多个NamedTuple
映射到一个列表中。
下面是代码示例-我的主要问题是双List
NamedTuple
和PeopleName
的{{1}}的映射-我不清楚如何做到这一点。如果将其分为两个步骤,则1 /将整行提取到通用PeopleAge
中,然后2 /将记录拆分为不同的NamedTupe
NamedTuple
和PeopleName
PeopleAge
答案 0 :(得分:2)
此注释List[(PeopleName, PeopleAge)]
引发TypeError: Too many parameters for typing.List; actual 2, expected 1
。
具有2种不同类型的元组也应使用typing.Tuple
进行注释:
List[Tuple[PeopleName, PeopleAge]]
但是,要注释参数,最好使用抽象集合类型,例如Sequence
或Iterable
:
Demography = NamedTuple(
"Demography", [("names", Sequence[Tuple[PeopleName, PeopleAge]]), ("postalcodes", PeoplePC)],
)
我不是直接为每个组应用to_nested_tuple
,而是通过以下方式直接进行操作:
d = [Demography([(PeopleName(row['Name']), PeopleAge(row['Age'])) for _, row in group.iterrows()], PeoplePC(k))
for k, group in people.groupby("PostalCode")]
现在,结果将打印为:
[Demography(names=[(PeopleName(Name='tom'), PeopleAge(Age=10)), (PeopleName(Name='juli'), PeopleAge(Age=14))], postalcodes=PeoplePC(PostalCode='ab 11')),
Demography(names=[(PeopleName(Name='nick'), PeopleAge(Age=15))], postalcodes=PeoplePC(PostalCode='ab 22'))]
答案 1 :(得分:1)
使用list(df.itertuples())
,其中df
是您的数据框。