如何将namedtuple转换为元组

问题描述 投票:1回答:3

怎么做this的反面?

我有一个通过迭代pandas数据帧构建的namedtuples列表:

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

如何将这个namedtuples列表转换为元组列表?请注意,itertuples()返回namedtuples。

python tuples namedtuple
3个回答
4
投票

你只需通过tuple()构造函数:

>>> from collections import namedtuple

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

2
投票

首先,不要在内置之后命名变量。

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

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

1
投票

你可以这样做。只需将namedtuple中的元组构造为param。

>>> 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,)]
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.