我已经在namedtuples上查看了Python文档,但我似乎无法弄清楚它可以采用的法律数据类型。或者它对我来说并不是直接显而易见的。
可以说它可以采用任何数据类型(例如int,float,string,tuple,list,dict等)吗?是否有任何数据类型无法插入到命名元组
中这个问题源于我需要一个有两个列表的命名元组。基本上我想要做的就是这样:
from Collections import namedtuple
list1 = [23,45,12,67]
list2 = [76,34,56,23]
TwoLists = namedtuple("TwoLists", ['x','y'])
tulist = TwoLists(x=list1, y=list2)
type(tulist)
<class '__main__.TwoLists'>
type(tulist.x)
<class 'list'>
print(tulist.x)
[23,45,12,67]
print(tulist.y)
[76,34,56,23]
这似乎至少与列表一起使用。
一些快速的Google搜索没有导致任何示例,这就是为什么我为尝试插入列表的任何其他人添加了代码摘录(来自python的交互模式)进入一个namedtuple并需要一个例子。
答案 0 :(得分:1)
我试图根据文档回答:
&#34;命名元组为元组中的每个位置指定含义,并允许更易读,自我记录的代码。它们可以在使用常规元组的任何地方使用,并且它们增加了按名称而不是位置索引访问字段的功能。&#34;来自https://docs.python.org/3/library/collections.html#collections.namedtuple
&#34;元组的项是任意Python对象&#34;从 https://docs.python.org/3/reference/datamodel.html#objects-values-and-types
答案 1 :(得分:0)
如果没有明确指定,任何 Python对象都有效。
答案 2 :(得分:0)
任何python对象均有效。如果要将特定的数据类型强制为namedtuple,则可以创建一个从具有指定数据类型的namedtuple继承的类,如下所示(取自https://alysivji.github.io/namedtuple-type-hints.html):
编辑:请注意,以下内容仅适用于python 3.6 +
from typing import List, NamedTuple
class EmployeeImproved(NamedTuple):
name: str
age: int
title: str
department: str
job_description: List
emma = EmployeeImproved('Emma Johnson',
28,
'Front-end Developer',
'Technology',
['build React components',
'test front-end using Selenium',
'mentor junior developers'])
编辑:在3.5中,您可以执行以下操作:
import typing
EmployeeImproved = typing.NamedTuple("EmployeeImproved",[("name",str),("age",int),("title",str),("department",str),("job_description",List)])
..并且在3.4及更早版本中,我相信您不走运(如果我错了,请纠正我)