如何将 namedtuple 转换为元组

How to cast namedtuple into tuple

如何做this的相反操作?

我有一个通过迭代 pandas 数据框构建的命名元组列表:

list = []
for currRow in dataframe.itertuples():
    list.append(currRow)

如何将这个命名元组列表转换为元组列表?注意 itertuples() returns namedtuples.

你只是把它通过 tuple() 构造函数:

>>> from collections import namedtuple

>>> foo = namedtuple('foo', ('bar', 'baz'))
>>> nt = foo(1,2)
>>> nt
foo(bar=1, baz=2)
>>> tuple(nt)
(1, 2)

首先,不要用内置函数命名变量。

要回答你的问题,你可以只使用 tuple 构造函数;假设您的来源 list 被命名为 l:

l_tuples = [tuple(t) for t in l]

你可以做到这一点。只需从 namedtuple 构造元组作为参数。

>>> X = namedtuple('X', 'y')
>>> x1 = X(1)
>>> x2 = X(2)
>>> x3 = X(3)
>>> x_list = [x1, x2, x3]
>>> x_tuples = [tuple(i) for i in x_list]
>>> x_tuples
[(1,), (2,), (3,)]
>>>