Home > database >  How to create sublists out of a list with strings?
How to create sublists out of a list with strings?

Time:10-30

Having a Python list like the following one:

list1 = [ "abc", "def", "ghi" ]

How can I obtain sub-lists for each character of the strings ?

list3 = [ ["a"], ["b"], ["c"] ]

list4 = [ ["d"], ["e"], ["f"] ]

list5 = [ ["g"], ["h"], ["i"] ]

CodePudding user response:

Do not generate variables programmatically, this leads to unclear code and is often a source of bugs, use a container instead (dictionaries are ideal).

Using a dictionary comprehension:

list1 = [ "abc", "def", "ghi" ]

lists = {'list%s' % (i 3): [[e] for e in s]] 
         for i,s in enumerate(list1)}

output:

>>> lists
{'list3': [['a'], ['b'], ['c']],
 'list4': [['d'], ['e'], ['f']],
 'list5': [['g'], ['h'], ['i']]}

>>> lists['list3']
[['a'], ['b'], ['c']]

NB. you could also simply use the number as key (3/4/5)

CodePudding user response:

To get a list from a string use list(string)

list('hello') # -> ['h', 'e', 'l', 'l', 'o']

And if you want to wrap the individual characters in a list do it like this:

[list(c) for c in ('hello')]

But that is useful only if you want to change the list afterward.

Note that you can index a string like so

'hello'[2] # --> 'l'

CodePudding user response:

This is how to break a list then break it into character list.

list1 = ["abc", "def", "ghi"]
list3 = list(list1[0])
list4 = list(list1[1])
list5 = list(list1[2])
  • Related