我编写了这个函数来将元组列表转换为列表列表.这样做有更优雅/ 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
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 50
您可以使用列表理解:
>>> 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]]
Run Code Online (Sandbox Code Playgroud)
Gar*_*tty 20
虽然名单理解是一个完全有效的答案,因为你只是改变类型,它可能是值得考虑的替代方案,该map()内置:
>>> list_of_tuples = [(1, 2), (4, 5)]
>>> map(list, list_of_tuples)
[[1, 2], [4, 5]]
Run Code Online (Sandbox Code Playgroud)
在map()内置的简单应用可调用给定迭代的每个元素.这使得它对这项特殊任务有益.一般来说,列表推导更具可读性和效率(因为map()你需要做任何复杂的事情lambda),但是你想简单地改变类型,map()可以非常清晰和快速.
请注意,我在这里使用2.x,所以我们得到一个列表.在3.x中你会得到一个可迭代的(这是懒惰的),如果你想在3.x中有一个列表,那就简单地做list(map(...)).如果您对可用的迭代很好,则在2.x中itertools.imap()提供一个惰性map().
| 归档时间: |
|
| 查看次数: |
29921 次 |
| 最近记录: |