Ran
Ran

Reputation: 725

Split a string and save them to a list with Python

I have a string that I inserted a space into it in all different positions and saved them to a list. Now this list of strings with space in them, I want to split those strings and put the output in one list, when am doing this, it happens that am having multiple list inside:

This is the code am working on:

var ='sans'
res = [var[:i]+' '+var[i:] for i in range(len(var))]
// The previous line: AM adding a space to see maybe that would generate other words
cor = [res[i].split() for i in range (len(res))]

And this is the output am getting:

>>> cor
[['sans'], ['s', 'ans'], ['sa', 'ns'], ['san', 's']]

What am expecting:

>>> cor
    ['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

Am new to python, I don't know what am missing.

Thanks

Upvotes: 3

Views: 9297

Answers (5)

user9158931
user9158931

Reputation:

You could do something like this in one line without importing any module :

var ='sans'

final=[]
list(map(lambda x:list(map(lambda y:final.append(y),x)),[(var[i:]+' '+var[:i]).split() for i in range(0,len(var))]))
print(final)

output:

['sans', 'ans', 's', 'ns', 'sa', 's', 'san']

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26315

You coud always use map() to split each string in res:

list(map(str.split, res))

Which gives:

[['sans'], ['s', 'ans'], ['sa', 'ns'], ['san', 's']]

Then you can use itertools.chain.from_iterable to flatten the list:

list(chain.from_iterable(map(str.split, res)))

Which Outputs:

['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

Upvotes: 1

pault
pault

Reputation: 43504

An alternative approach:

cor = " ".join(res).split()

Output:

['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

Explanation

" ".join(res) will join the individual strings in res with a space in between them. Then calling .split() will split this string on whitespace back into a list.

EDIT: A second approach that doesn't involve the intermediate variable res, although this one isn't quite as easy on the eyes:

cor = [var[:i/2+1] if i%2==1 else var[i/2:] for i in range(2*len(var)-1)]

Basically you flip between building substrings from the front and the back.

Upvotes: 6

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

First of all, your

[res[i].split() for i in range (len(res))]

is a complicated unpythonic way to do the same as this:

[r.split() for r in res]

Now... the problem is that you treat r.split() as your end result. You should instead use it as a source to treat it further:

[s for r in res for s in r.split()]

Upvotes: 3

Dekel
Dekel

Reputation: 62556

If you have a list

cor = [['sans'], ['s', 'ans'], ['sa', 'ns'], ['san', 's']]

And you want to flatten it, you can use the following:

flat = [x for y in cor for x in y]

The output will be:

['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

You can also make that directly with the res variable:

cor = [x for y in [res[i].split() for i in range (len(res))] for x in y]

Upvotes: 2

Related Questions