使用列表理解减少将列表列表转换为元组的函数

2024-06-02 08:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想改变这个函数使用列表理解,以便它将有1或到行。函数在包含元组的元组中转换包含列表的列表

def lol(lista):
        novotuplo = ()
            for i in range(len(lista)):
                novotuplo += (tuple(lista[i]),)

            return novotuplo

Tags: 函数in列表forlenreturndefrange
3条回答

您可以map将项添加到tuple()构造函数:

tuple(map(tuple, lista))

我想应该这样做。你知道吗

novotuplo = tuple(tuple(item) for item in lista)

如果你想要函数形式,这是一种方法。这里不需要索引,因为lst in lista直接迭代元素。你知道吗

lista = [[1],[2],[3]]
def lol(lista):
    novotuplo = tuple(tuple(lst) for lst in lista)
    return novotuplo

print (lol(lista))
# ((1,), (2,), (3,))

相关问题 更多 >