简体   繁体   English

从元组创建命名元组?

[英]Creating named tuple from tuple?

I'm working with kinterbasdb to select and update some data from databases of 1998 (yes, unfortunatly :(). And the API of kinterbasdb return the values from queries in tuples, for example: 我正在与kinterbasdb一起从1998年的数据库中选择和更新一些数据(是的,不幸的是:()。kinterbasdb的API返回元组查询中的值,例如:

connection = connect(dsn="database.gdb", user="MYUSER", password="MYPASSWORD")
cursor = connection.cursor()
cursor.execute("SELECT * FROM TABLE_X")
result = cursor.fetchone() # tuple => (value1, value2, value3, value4, value5)

And i would like to map this tuple to a named tuple. 我想将此元组映射到一个命名的元组。 Is it possible? 可能吗?

I'm using Python 2.7.13 (i was able to update the kinterbasdb module to make it work... at least) 我正在使用Python 2.7.13(我能够更新kinterbasdb模块以使其正常运行...至少)

Just pass your tuple to the namedtuple constructor as expanded args using * . 只需使用*将元组作为扩展的args传递给namedtuple构造函数。

In [1]: from collections import namedtuple

In [2]: Response = namedtuple('Response', ['thing1', 'thing2', 'thing3', 'thing4'])

In [3]: mytuple = (1, 2, 3, 4)

In [4]: Response(*mytuple)
Out[4]: DBResponse(thing1=1, thing2=2, thing3=3, thing4=4)

Example: 例:

from collections import namedtuple
t=("value1", "value2", "value3", "value4", "value5")
Data=namedtuple("Data",["v1","v2","v3","v4","v5"])
nt=Data(*t)
>>> nt
Data(v1='value1', v2='value2', v3='value3', v4='value4', v5='value5')

Or use the _make method: 或使用_make方法:

>>> Data._make(t)
Data(v1='value1', v2='value2', v3='value3', v4='value4', v5='value5')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM