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?

+3


source to share


4 answers


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).

+5


source


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

+1


source


Here's one quick fix:

x=['+27', '05', '1995 F']
finlist=[]
for element in x:
    for val in element.split(" "):
        finlist.append(val)
print finlist

      

Or:

x=['+27', '05', '1995 F']
finlist=[]
for element in x:
    finlist.extend(element.split(" "))
print finlist

      

+1


source


"How to ensure that 2nd item is not the output of this sub-list?" Use extend

for this:

In [32]: result = []

In [34]: inp = ['+27', '05', '1995 F']

In [35]: [result.extend(i.split()) for i in inp]
Out[35]: [None, None, None]

In [36]: result
Out[36]: ['+27', '05', '1995', 'F']

      

+1


source







All Articles