0

So I have a list in the following format:

list_1 = ['a,b,c','1,2,3','e,f,g']

which I made into sublists using

list_1 = [list_1[i:i+1] for i in range(0, len(list_1), 1)]

that output of that is

list_1 = [['a,b,c'],['1,2,3'],['e,f,g']]

but I would like to get it into this format:

list_1 = [['a','b','c'],['1','2','3'],['e','f','g']]

how would this be possible?

bruhsmh
  • 321
  • 2
  • 4
  • 12

2 Answers2

5
list_1 = [el.split(',') for el in list_1]
freakish
  • 54,167
  • 9
  • 132
  • 169
1
# you can also use map
list_1 = list(map(lambda x: x.split(','), list_1))

EDIT* : As was pointed out, in regard to performance, list comprehensions will win here for this task. To illustrate this, we can run a simulation on the task quite a few times.

import timeit
# List comprehension
timeit.timeit("""[el.split(',') for el in ['a,b,c','1,2,3','e,f,g']]""", number = 10000000)
# 6.5357

# using map
timeit.timeit("""list(map(lambda x: x.split(','), ['a,b,c','1,2,3','e,f,g']))""", number = 10000000)
# 9.1717
datawrestler
  • 1,527
  • 15
  • 17
  • Why the downvote @jamylak? Does this not work for you? – RoadRunner Feb 03 '18 at 07:16
  • @RoadRunner it's worse (less elegant and slower) than the answer by freakish so i'm trying to help discourage people from this solution – jamylak Feb 03 '18 at 07:30
  • The OP wasn't concerned about speed nor did they ask for the most pythonic way of doing it and it's an alternative way of achieving the objective that was originally asked for by the OP. The output results in the same thing. There are tons of posts that include alternative ways of doing things on SO. – datawrestler Feb 03 '18 at 19:19