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

前端 未结 3 1048
醉话见心
醉话见心 2020-12-01 09:04

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 bel

相关标签:
3条回答
  • 2020-12-01 09:47

    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')]
    
    0 讨论(0)
  • 2020-12-01 09:54
    [tuple(l) for l in nested_lst]
    
    0 讨论(0)
  • 2020-12-01 09:58

    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.

    0 讨论(0)
提交回复
热议问题