简体   繁体   中英

Convert list into list of lists

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

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

I want:

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

I tried:

list(list(my_list))

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']]
>>> 

Try This one Liner:-

map(lambda x:[x], my_list)

Result

In [1]: map(lambda x:[x], my_list)
Out[1]: [['banana'], ['mango'], ['apple']]
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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