Irv*_* H. 5 python list namedtuple
我查看了有关命名元组的 Python 文档,但我似乎无法弄清楚它可以采用哪些合法数据类型。或者也许这对我来说并不明显。
可以肯定地说它可以采用任何数据类型(例如 int、float、string、tuple、list、dict 等)吗?是否有任何数据类型无法插入到命名元组中
这个问题是因为我需要一个有 2 个列表的命名元组。本质上我想做的是这样的:
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]
Run Code Online (Sandbox Code Playgroud)
这似乎至少适用于列表。
一些快速的谷歌搜索没有产生任何示例,这就是为什么我为任何其他尝试将列表插入命名元组并需要示例的人添加了代码摘录(来自Python的交互模式)。
Any python object is valid. If you want to force specific datatypes to the namedtuple, you can create a class that inherits from namedtuple with specified data types as follows (taken from https://alysivji.github.io/namedtuple-type-hints.html):
edit: note the below only works in 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'])
Run Code Online (Sandbox Code Playgroud)
edit: in 3.5, you can do this:
import typing
EmployeeImproved = typing.NamedTuple("EmployeeImproved",[("name",str),("age",int),("title",str),("department",str),("job_description",List)])
Run Code Online (Sandbox Code Playgroud)
.. and in 3.4 and earlier, I believe you are out of luck (someone correct me if I am wrong)
| 归档时间: |
|
| 查看次数: |
3311 次 |
| 最近记录: |