Divide each line in the list into numbers and numbers without numbers.
I have a list of strings:
x = ['+27', '05', '1995 F']
I need a code that outputs this:
['+', '27', '05', '1995', 'F']
I was thinking about using a function .split()
for the last item, so I wrote this code:
x=['+27', '05', '1995 F']
x[2]=x[2].split()
Output:
['+27', '05', ['1995', 'F']]
How do I ensure the 2nd item is not a sub-list and output this instead?
['+27', '05','1995','F']
Should I use insert
and del
?
I wrote this for the first element using insert
and del
:
x=x.split("/")
x.insert(0,x[0][0])
x.insert(1,x[1][1:])
del x[2]
Output:
['+', '27', '05', '1995 F']
Is there a better way?
source to share
Here's a solution using itertools.groupby()
and str.isdigit()
in an expression:
>>> from itertools import groupby
>>> x=['+27', '05', '1995 F']
>>> [''.join(g).strip() for s in x for k, g in groupby(s, str.isdigit)]
['+', '27', '05', '1995', 'F']
This works by breaking each line in x
into groups of characters based on whether they are numbers or not, then appending those groups to the lines, and finally removing spaces from the resulting lines.
As you can see, unlike the other solutions presented so far, it splits "+27" into "+" and "27" (as your question says what you want).
source to share
x = ['+27', '05', '1995 F']
l = []
[l.extend(e.split()) for e in x]
print l
and check this for more convenient Smooth (wrong) list of lists
source to share