将列表中的每个元组插入到另一个元组中,这样我就会得到一个元组列表

Insert every tuple in a list to another tuple so I will have a list of tuples of tuples

我正在尝试将以下元组列表转换为包含原始元组的元组的列表。 例如,我们有以下列表:

arr1 = [(1, 2), (2, 3), (4, 5)]

我尝试进行以下转换,但没有成功:

arr1_tuples = [tuple(item) for item in arr1]

期望的输出是:

[((1, 2)), ((2, 3)), ((4, 5))]

你想要的输出是不可能的(单个元素 tuples 将有一个带尾随逗号的 repr),但是你想要的数据结构可以通过以下方式实现:

arr1_tuples = [(item,) for item in arr1]

将每个 item 包裹在一个 tuple 中。括号不是必需的,但没有它们很容易错过单独的尾随逗号。

如果 printed,结果将是:

[((1, 2),), ((2, 3),), ((4, 5),)]
      # ^          ^          ^ Commas unavoidable in one-tuples; otherwise matches request

使用map:

arr1 = [(1, 2), (2, 3), (4, 5)]

arr1_tuples = map(lambda x:(x,), arr1)

print(list(arr1_tuples))

输出:

[((1, 2),), ((2, 3),), ((4, 5),)]

lambda x:(x,) 将接受一个元素,并且 return 它在一个元组中。