将元组列表转换为列表列表

2024-10-06 18:18:43 发布

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

我编写此函数是为了将元组列表转换为列表列表。有没有更优雅/更像Python的方法?

def get_list_of_lists(list_of_tuples):
    list_of_lists = []                                                          
    for tuple in list_of_tuples:
        list_of_lists.append(list(tuple))

    return list_of_lists

Tags: of方法函数in列表forgetreturn
2条回答

您可以使用list comprehension

>>> list_of_tuples = [(1, 2), (4, 5)]
>>> list_of_lists = [list(elem) for elem in list_of_tuples]

>>> list_of_lists
[[1, 2], [4, 5]]

虽然列表理解是一个完全有效的答案,因为您只是在更改类型,但可能值得考虑另一种选择,the ^{} built-in

>>> list_of_tuples = [(1, 2), (4, 5)]
>>> map(list, list_of_tuples)
[[1, 2], [4, 5]]

内置的map()只需对给定iterable的每个元素应用一个callable。这使它适合这个特殊的任务。一般来说,列表理解更具可读性和效率(对于使用map()执行任何复杂的操作,您需要lambda),但是如果您只想更改类型,map()可以非常清晰和快速。

注意,我这里用的是2.x,所以我们得到一个列表。在3.x中,您将得到一个iterable(这很懒),如果您想在3.x中得到一个列表,只需list(map(...))。如果您可以使用iterable,那么^{}在2.x中提供了一个懒惰的map()

相关问题 更多 >