Convert list into list of lists

前端 未结 3 1235
攒了一身酷
攒了一身酷 2020-11-29 08:52

I want to convert list into list of list. Example:

my_list = [\'banana\', \'mango\', \'apple\']

I want:

my_list = [[\'banan         


        
相关标签:
3条回答
  • 2020-11-29 09:20
        lst = ['banana', 'mango', 'apple']
        lst_of_lst = []
        for i in lst:
            spl = i.split(',')
            lst_of_lst.append(spl)
        print(lst_of_lst)
    

    first create an empty list and then iterate through your list. split each list and append them to your empty list.

    0 讨论(0)
  • 2020-11-29 09:23

    Try This one Liner:-

    map(lambda x:[x], my_list)
    

    Result

    In [1]: map(lambda x:[x], my_list)
    Out[1]: [['banana'], ['mango'], ['apple']]
    
    0 讨论(0)
  • 2020-11-29 09:34

    Use list comprehension

    [[i] for i in lst]
    

    It iterates over each item in the list and put that item into a new list.

    Example:

    >>> lst = ['banana', 'mango', 'apple']
    >>> [[i] for i in lst]
    [['banana'], ['mango'], ['apple']]
    

    If you apply list func on each item, it would turn each item which is in string format to a list of strings.

    >>> [list(i) for i in lst]
    [['b', 'a', 'n', 'a', 'n', 'a'], ['m', 'a', 'n', 'g', 'o'], ['a', 'p', 'p', 'l', 'e']]
    >>> 
    
    0 讨论(0)
提交回复
热议问题