How to convert nested list of lists into a list of

2019-01-14 20:53发布

I am trying to convert a nested list of lists into a list of tuples in 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')]

3条回答
何必那么认真
2楼-- · 2019-01-14 21:23

You can use 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.

查看更多
We Are One
3楼-- · 2019-01-14 21:40
[tuple(l) for l in nested_lst]
查看更多
唯我独甜
4楼-- · 2019-01-14 21:43

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')]
查看更多
登录 后发表回答