简体   繁体   English

如何将嵌套列表列表转换为 python 3.3 中的元组列表?

[英]How to convert nested list of lists into a list of tuples in python 3.3?

I am trying to convert a nested list of lists into a list of tuples in Python 3.3.我正在尝试将嵌套列表列表转换为 Python 3.3 中的元组列表。 However, it seems that I don't have the logic to do that.但是,我似乎没有这样做的逻辑。

The input looks as below:输入如下所示:

>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]

And the desired ouptput should look as exactly as follows:所需的输出应如下所示:

nested_lst_of_tuples = [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]

Just use a list comprehension:只需使用列表理解:

nested_lst_of_tuples = [tuple(l) for l in nested_lst]

Demo:演示:

>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
>>> [tuple(l) for l in nested_lst]
[('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]

You can use map() :您可以使用map()

>>> list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))
[('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]

This is equivalent to a list comprehension, except that map returns a generator instead of a list.这等效于列表推导式,除了map返回生成器而不是列表。

[tuple(l) for l in nested_lst]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM