Reputation: 1
I plan to write a python function that can change the structure of a list. The input is:
list=[['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
The output is:
list=[['A','B','C','D','E','F'],['1','2','3','4','5','6']]
I know I need the split()
and append()
. The confusing part is the loops.
Thanks so much!!
Upvotes: 0
Views: 72
Reputation: 25833
Sometimes it's best not to over think it. Lets start with just one piece of your problem, ['A B C','D E F']
. You want to split each string, and put parts into a result list. Let's start by writing that function. You've correctly stated that this can be done using split
/append
, but lists also happen to have an extend
method which will save you a few lines of code.
def as_char(seq):
result = []
for item in seq:
result.extend(item.split())
return result
Now you want to apply that function to every list in your input. For that you can use map
for a list comprehension.
sample_input = [['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
output = map(as_char, sample_input)
# or
output = [as_char(item) for item in sample_input]
Upvotes: 3
Reputation: 180481
Join your subelements making sure to leave a space when joining then split on whitespace to split into individual elements and remove any trailing whitespace.
print([ " ".join(sub).split() for sub in l])
[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]
If you only have two subelements unpack and split using str.format to allow a space between for splitting:
print([ "{} {}".format(a,b).split() for a,b in l ])
[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]
If you are using list as a variable name then don't as you will be shadowing the builtin list which often leads to more questions on SO...
Upvotes: 2
Reputation: 16711
Use the join method to join the contain elements in the nested lists. Then split at the spaces.
my_list = [['A B C', 'D E F'], ['1 2 3 ', '4 5 6']]
my_list = [' '.join(i).split() for i in my_list]
Upvotes: 4
Reputation: 19753
How about this:
>>> my_list = [['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
>>> map(lambda x:x.split(), map(" ".join, my_list))
[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]
Upvotes: 0