Python 将元组列表转换为列表列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14831830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a list of tuples to a list of lists
提问by woollybrain
I've written this function to convert a list of tuples to a list of lists. Is there a more elegant / Pythonic way of doing this?
我编写了这个函数来将元组列表转换为列表列表。有没有更优雅/ Pythonic 的方式来做到这一点?
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
采纳答案by Rohit Jain
You can use 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]]
回答by Gareth Latty
While the list comprehension is a totally valid answer, as you are just changing type, it might be worth considering the alternative, the map()built-in:
虽然列表推导式是一个完全有效的答案,但由于您只是在更改类型,因此可能值得考虑替代方法,即map()内置的:
>>> list_of_tuples = [(1, 2), (4, 5)]
>>> map(list, list_of_tuples)
[[1, 2], [4, 5]]
The map()built-in simply applies a callable to each element of the given iterable. This makes it good for this particular task. In general, list comprehensions are more readable and efficient (as to do anything complex with map()you need lambda), but where you want to simply change type, map()can be very clear and quick.
在map()内置的简单应用可调用给定迭代的每个元素。这使它非常适合这项特定任务。在一般情况下,列表内涵是更具可读性和效率(如做任何复杂的带map()你需要lambda),但要根本改变类型,map()可以非常清晰和快捷。
Note that I'm using 2.x here, so we get a list. In 3.x you will get an iterable (which is lazy), if you want a list in 3.x, simply do list(map(...)). If you are fine with an iterable for your uses, itertools.imap()provides a lazy map()in 2.x.
请注意,我在这里使用的是 2.x,因此我们得到了一个列表。在 3.x 中你会得到一个可迭代的(这是惰性的),如果你想要一个 3.x 中的列表,只需执行list(map(...)). 如果您可以使用迭代器,请在 2.x 中itertools.imap()提供惰性map()。

